In my sample MVC application I have a model
class SampleModel
{
public int Id { get; set; }
public string Name { get; set; }
public List<Certification> Certifications { get; set; }
}
class Certification
{
public int Id { get; set; }
public string CertificationName { get; set; }
public int DurationInMonths { get; set; }
}
My View (I need the certification details to be shown in a partial view)
@model SampleApplication.Model.SampleModel
<!-- other code... -->
@using (Html.BeginForm("SaveValues","Sample", FormMethod.Post, new { id= "saveForm" }))
{
@Html.HiddenFor(m => m.Id, new { id = "hdnID" })
@Html.TextBoxFor(m => m.Name, new { id = "txtName" })
@{Html.RenderPartial("_CertDetails.cshtml", Model.Certifications);}
<input type="submit" id="btnSubmit" name="btnSubmit" value="Update" />
}
Partial View
@model List<SampleApplication.Model.Certification>
<!-- other code... -->
@if (@Model != null)
{
for (int i = 0; i < @Model.Count; i++)
{
@Html.HiddenFor(m => m[i].Id , new { id = "CId" + i.ToString() })
@Html.TextBoxFor(m => m[i].CertificationName,new{ id ="CName" + i.ToString() })
@Html.TextBoxFor(m => m[i].DurationInMonths,new{ id ="CDur" + i.ToString() })
}
}
Controller
[HttpPost]
public ActionResult SaveValues(SampleModel sm)
{
//Here i am not getting the updated Certification details (in sm)
}
How I get the updated values of partial view in my controller after the form post? I am able to get the updated certification values when I am not using partialview. Is this the right way or should I follow some other methods?
Oh Nooo... It was my mistake :( . I gave Certification List as my partialview model
@model List<SampleApplication.Model.Certification>
But I should use the same model(Main page model) in the partial view also.
@model SampleApp.Models.SampleModel
In the partial view the coding will be like
@for (int i = 0; i < @Model.Certifications.Count; i++)
{
@Html.HiddenFor(m => m.Certifications[i].Id, new { id = "CId" + i.ToString() })
@Html.TextBoxFor(m => m.Certifications[i].CertificationName, new { id = "CName" + i.ToString() })
@Html.TextBoxFor(m => m.Certifications[i].DurationInMonths, new { id = "CDur" + i.ToString() })<br /><br />
}
Now i am getting the updated values in my controller.
Thanks @Chris Pratt for the hint.