How to get List<Model> Object in HTTP POST
I have two model classes:
public class UserModel
{
public Guid Id { get; set; }
public string EmailAddress { get; set; }
public string LoginName { get; set; }
public string Password { get; set; }
}
public class GroupModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<UserModel> Users { get; set; }
}
I created a View (Create.Aspx) by inheriting GroupModel class.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MyApp.Models.GroupModel>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Create</title>
</head>
<body>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Id) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Id) %>
<%: Html.ValidationMessageFor(model => model.Id) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Name) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Name) %>
<%: Html.ValidationMessageFor(model => model.Name) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</body>
</html>
It is generating only two fields (Id, Name) in my aspx view. Also I am able to get the form data in the Model class object in ё[HttpPost]ё request which contains the data for ID and NAME field in controller.
[HttpPost]
public ActionResult Create(GroupModel groupModel)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
How can I get the data in List<UserModel>
object ?
I am thinking to Put a List 开发者_如何学Ccontrol with checkboxes containing Users. Then catch them using FormCollection
object in controller.
Please suggest if I am in correct way or is there any better way to do this?
You could use an editor template (~/Views/Shared/EditorTemplates/UserModel.ascx
):
<%@ Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<YourApp.Models.UserModel>" %>
<%: Html.TextBoxFor(model => model.Id) %>
<%: Html.ValidationMessageFor(model => model.Id) %>
<%: Html.TextBoxFor(model => model.EmailAddress) %>
<%: Html.ValidationMessageFor(model => model.EmailAddress) %>
<%: Html.TextBoxFor(model => model.LoginName) %>
<%: Html.ValidationMessageFor(model => model.LoginName) %>
...
And then inside the main view you could include this editor template:
...
<%: Html.EditorFor(model => model.Users) %>
<p>
<input type="submit" value="Create" />
</p>
This will invoke the editor template for each item in the Users
collection. So you could fill this collection in your GET action with some users and you will be able to edit their information inside the form.
精彩评论