【发布时间】:2019-10-01 09:30:44
【问题描述】:
我创建了添加客户的表单。我用 Viewmodel 渲染了客户页面。查看Model类如下,
public class CustomerViewModel
{
public IEnumerable<MemberShipType> MemberShipTypes { get; set; }
public Customer Customers { get; set; }
}
public class Customer
{
[Display(Name ="Customer ID")]
public int CustomerId { get; set; }
[Required(ErrorMessage = "Please enter customer name")]
[StringLength(255)]
[Display(Name ="Customer Name")]
public string CustomerName { get; set; }
public MemberShipType MemberShipType { get; set; }
[Required(ErrorMessage = "Please select membership type")]
[Display(Name = "Membership Type")]
public byte MembershipTypeId { get; set; }
}
public class MemberShipType
{
[Display(Name ="Membership Id")]
public byte Id { get; set; }
[Required]
[Display(Name = "Subscription Plan")]
public string Name { get; set; }
}
添加该类后,我们创建了 Action 以使用单个模型类(不是 viewModel)保存客户表单数据
我使用 Viewmodel 创建了客户表单,以显示会员类型数据。
使用以下代码可以很好地呈现 UI。但是,我无法在 action 方法中获取模型数据。
如果我直接在动作数据中使用视图模型就可以了。问题需要将所有视图模型属性映射到特定模型。
每次映射模型属性都需要更多时间。
谁能知道如何直接使用实体框架添加方法和客户模型(不是视图模型)
@using (Html.BeginForm("Save", "Customer", FormMethod.Post))
{
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Customers.CustomerName, htmlAttributes:
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(m => m.Customers.CustomerName,
new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.Customers.CustomerName, "",
new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Customers.MembershipTypeId, htmlAttributes:
new { @class = "control-label col-md-2" })
<div class="col-lg-10">
@Html.DropDownListFor(m => m.Customers.MembershipTypeId,
new SelectList(Model.MemberShipTypes, "Id", "Name"),
"Please Select", new {@class = "form-control"})
@Html.ValidationMessageFor(m => m.Customers.MembershipTypeId,
"",
new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<input type="reset" value="Reset" class="btn btn-default" />
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
}
下面的动作模型总是返回null。
[System.Web.Mvc.HttpPost]
public ActionResult Save(Customer customer)
{
if (customer.CustomerId == 0)
{
_context.Customer.Add(customer);
_context.SaveChanges();
}
}
我得到一个客户模型为空。如果我通过 customerViewModel 数据来了。谁能知道如何直接获取模型类中的数据?
【问题讨论】:
标签: c# model-view-controller asp.net-mvc-5