I'm learning MVC5 and I'm trying to implement a simple page to add and display students. The question takes lot of space but is extremely basic.
So here is the model:
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Here are the action methods:
public ActionResult Index()
{
return View(db.Students.ToList());
}
public ActionResult Create()
{
return PartialView();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return PartialView();
}
return PartialView(student);
}
Here is the Parent view: Index.cshtml
@model IEnumerable<MVCAjax.Models.Student>
<h2>Index</h2>
<div class="row" id="myformbase">
<div class="col-md-6">
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
</tr>
}
</table>
</div>
<div class="col-md-6">
@Html.Action("Create")
</div>
</div>
Here is the child view: Create.cshtml
@model MVCAjax.Models.Student
@using (Ajax.BeginForm("Create", "Student", new AjaxOptions { UpdateTargetId = "myform" }))
{
<div id="myform">
<h2>Create</h2>
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</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">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</div>
}
Now I've have few issues:
I've a little experience of MVC4 and there if I used to pass (in AjaxOptions) the Id of div that contained both the child divs (in my case "myformbase") then it used to update it. But not sure why this doesn't work in MVC5.
ModelState.Clear();
after you have saved record in to database;Try to change UpdateTargetId to the base container ID:
@using (Ajax.BeginForm("Create", "Student", new AjaxOptions { UpdateTargetId = "myformbase" })){...}