Answer the question
In order to leave comments, you need to log in
How to properly bind a form to a complex model?
Good evening!
I am developing a web application on ASP.NET MVC 5.
There is a partial view:
@model AndroidManagerApplication.Models.ViewModels.AndroidsAssignedToJobViewModel
@using (Html.BeginForm("EditJobAndroids", "Home", FormMethod.Post))
{
if (Model.AndroidList.Count() == 0)
{
<div class="text-black-50 text-black-50">
<p class="text-center">No androids</p>
</div>
}
else
{
<table class="table table-bordered">
<thead>
<tr>
<td>Is assigned</td>
<td>Name</td>
</tr>
</thead>
@for (var i = 0; i < Model.AndroidList.Count(); i++)
{
<tr>
<td hidden="hidden"><input type="hidden" name="AndroidList[@i].TheAndroid" value=@Model.AndroidList.ElementAt(i).TheAndroid/></td>
<td><input type="checkbox" class="form-control" name="AndroidList[@i].IsAssignedToJob"/></td>
<td>@Html.Label(Model.AndroidList.ElementAt(i).TheAndroid.Name)</td>
</tr>
}
</table>
<input type="submit" class="btn" />
}
}
public class AndroidsAssignedToJobViewModel
{
public ICollection<ExtendedAndroid> AndroidList { get; set; }
public Job CurrentJob { get; set; }
public AndroidsAssignedToJobViewModel() { }
public AndroidsAssignedToJobViewModel(Job currentJob, IEnumerable<Android> androidList)
{
List<ExtendedAndroid> extendedAndroidList = new List<ExtendedAndroid>() { };
CurrentJob = currentJob;
foreach (var android in androidList)
{
var extendedAndroid = new ExtendedAndroid()
{
TheAndroid = android,
IsAssignedToJob = currentJob == android.CurrentJob
};
extendedAndroidList.Add(extendedAndroid);
}
AndroidList = extendedAndroidList;
}
public class ExtendedAndroid
{
public Android TheAndroid { get; set; }
public bool IsAssignedToJob { get; set; }
}
}
[HttpPost]
public ActionResult EditJobAndroids(AndroidsAssignedToJobViewModel model)
{
foreach (var item in model.AndroidList)
{
if (item.IsAssignedToJob)
item.TheAndroid.ChangeJob(model.CurrentJob);
}
return Redirect(Request.UrlReferrer.ToString());
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question