The problem is:
I have the an Ajax.BeginForm, that essentially consists of two dropdownlists and the submit button. I want MVC 3 validation to kick in if the user doesn't select an option from both of the dropdownlists.
This is isn't happening. Instead, the page opens with the ValidationMessages showing beside the ddls, and if there is a submission with invalid data, no validation summary gets shown.
The code is:
using (Ajax.BeginForm(MVC.Admin.TutorEditor.AddTutorCourse(Model.TutorName, 0, 0),
new AjaxOptions
{
UpdateTargetId = "TutorCourses",
OnBegin = "isValidPleaseWait",
LoadingElementId = "PleaseWait"
},
new { name = "AddTutorCourseForm", id = "AddTutorCourseForm" }))
{
Html.ValidationSummary("Sorry, there was an error. Please check below and try again:");
<fieldset>
<legend>Add Course</legend>
<div class="editor-label">
@Html.LabelFor(model => model.AllCourses)
@Html.DropDownList("CourseId", Model.AllCourses, "-- Choose Course --", new { style = "width:180px;" })
@Html.ValidationMessage("CourseId", "*: Required")
</div>
<div class="editor-label">
@Html.LabelFor(model => model.TutorRoles)
@Html.DropDownList("TutorRoleId", Model.TutorRoles, "-- Choose Role --", new { style = "width:180px;" })
@Html.ValidationMessage("TutorRoleId", "*: Required")
</div>
<input type="submit" value="Add Course" />
</fieldset>
}
The AddTutorCourse Action is:
[HttpPost]
public virtual ActionResult AddTutorCourse(string username, int CourseId, int TutorRoleId)
{
service.SetTutor(username);
if (CourseId == 0) ModelState.AddModelError("CourseId", "You did not choose a Course");
if (TutorRoleId == 0) ModelState.AddModelError("TutorRoleId", "You did not choose a Tutor Role");
if(ModelState.IsValid)
{
service.AddTutorToCourse(CourseId, TutorRoleId);
}
if (Request.IsAjaxRequest())
{
return PartialView(Views.TutorCoursesPartial, service.ViewModel);
}
else
{
return View(Views.Details, service.ViewModel);
}
}
The included script files are:
<script id="script0" src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script id="script1" src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script id="script2" src="/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
<script id="script3" src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script id="script4" src="/jQueryUI/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script>
<script id="script5" src="/jQueryPlugins/Cookies/jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript" src="/Scripts/jquery.unobtrusive-ajax.min.js"></script>
What am I doing wrong!?