I'm new to MVC, please help on the below issue.
I have created Partial View which has few required field controls.
On the Index page, I'm showing employee list and also rendering the Partial View inside div control.
But when I say submit on the Partial View without entering any value, obviously
ModelState.IsValid
will be false due to required field, but I couldn't able to show the same Index page with validation error message. Instead of that, It's opening a new tab and showing partial view page along with validation error message.
How to show the same index page along with validation error messages without using new tab.
Employee Class:
public int EmployeeID { get; set; }
[Display(Name="Name")]
[Required(ErrorMessage="Please enter employee name.")]
public string EmployeeName { get; set; }
[Range(20, 60)]
public int Age { get; set; }
public int Gender { get; set; }
Partial View:
@using (Html.BeginForm("Save", "Employee", FormMethod.Post, new { id = "displayer" }))
{
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.EmployeeID)
<div class="form-group">
@Html.LabelFor(model => model.EmployeeName, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EmployeeName)
@Html.ValidationMessageFor(model => model.EmployeeName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Age, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Gender, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Gender)
@Html.ValidationMessageFor(model => model.Gender)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
}
Controller Action:
[HttpPost]
public PartialViewResult Save(Employee employee)
{
if (ModelState.IsValid)
{
return PartialView("Index", _employees);
}
ModelState.AddModelError("AddEmployee", "Please enter all mandatory fields.");
return PartialView("_onPageEdit", new Employee());
}
Index Page:
<a id="loadview">Load</a>
<div id="displayer" style="height:100px; width:400px;">
</div>
$('#loadview').click(function () {
$.ajax({
type: 'POST',
url: '@Url.Content("~/Employee/Loads")',
success: function (data) {
$('#displayer').html(data)
},
error: function (data) {
alert('Failed');
}
});
})
What I have tried:
I have tried to load div by using Ajax not able to achieve the same after validation.
$('#loadview').click(function () {
$.ajax({
type: 'POST',
url: '@Url.Content("~/Employee/Loads")',
success: function (data) {
$('#displayer').html(data)
},
error: function (data) {
alert('Failed');
}
});
})