I have a system consisting of main page that starts a form:
@model Stuvo_Intakeformulier.Models.CaterRequest
@using (Html.BeginForm(null, null, FormMethod.Post, new { id="fooData", @class="form-horizontal", role="form"}))
{
<div id="generalInfo" style="display:none">
@{Html.RenderPartial("Food", Model.foodInfo);}
</div>
<div id="studyInfo" style="display:none">
@{Html.RenderPartial("Drinks", Model.drinkInfo);}
<input type="submit" value="Bevestigen">
....
using a parent model
public class CaterRequest
{
public CaterRequest()
{
foodInfo = new Food();
drinkInfo = new Drinks();
}
public Food foodInfo { get; set; }
....
And child models like this:
public class Food
{
[Required(ErrorMessage = "BlaBla")]
public string name { get; set; }
}
Finally, the partial view looks like this:
@model Stuvo_Intakeformulier.Models.Food
<div class="form-group">
@Html.LabelFor(model => Model.name, "Naam: ", htmlAttributes: new { @class = "col-sm-2 control-label" })
<div class="col-sm-10">
@Html.TextBoxFor(model => Model.name, null ,htmlAttributes: new { @class = "form-control" })
</div>
<div class="col-sm-offset-2 col-sm-10">
@Html.ValidationMessageFor(model => Model.name)
</div>
</div>
Obviously when posting my model.foodInfo.name will be empty because of the fact that in my partial views the name attribute is name
instead of foodInfo.name
. I can solve this by changing @Html.TextBoxFor(model => Model.name..
with @Html.TextBox('foodInfo.name'
but then I lose all the advantages of my strongly typed partial view (especially the client side validation, which is something I absolutely need to have).
I was wondering what the best solution to this problem would be? Is there an easy way to solve this? What is the cleanest solution?
Basically I want to bind the data from my strongly typed partial views to my model in my normal view, while still maintaining the strongly typed views and validation stuff.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…