使用ViewModel时,对象不会从视图传递到控制器

时间:2018-07-13 08:09:25

标签: asp.net

*

伙计们需要您的帮助,以免数据无法传递到控制器。我遇到了从视图传递到控制器的示例数据。因此,每当我在action方法的参数中使用viewmodel时,都会正确传递发布的对象,但是当我使用在viewmodel内部的客户模型时,不会传递我尝试提交给数据库的数据。这是查看代码:

*

@model WebApplication2.Models.CustomerViewModel
@{
    ViewBag.Title = "CreateForm";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>CreateForm</h2>

@using(Html.BeginForm("Create", "Customer"))
{
    <div class="form-group">
        @Html.LabelFor(m=>m.Customers.Name)
        @Html.TextBoxFor(m=>m.Customers.Name, new { @class="form-control"})
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Customers.Birthdate)
        @Html.TextBoxFor(m => m.Customers.Birthdate, new { @class = "form-control" })
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Customers.MembershipTypeId)
        @Html.DropDownListFor(m => m.Customers.MembershipTypeId, new SelectList(Model.MembershipTypes, "Id", "Name"),"Select", new { @class = "form-control" })
    </div>
    <button type"submit" class="btn btn-primary">Save</button>
}

Controller code

  [HttpPost]
        public ActionResult Create(Customer customer)//data is not passed when I use Customer but is passed when CustomerViewModel is used
        {
            context.Customer.Add(customer);
            context.SaveChanges();
            return RedirectToAction("Index", "Customer");
        }

1 个答案:

答案 0 :(得分:0)

查看视图的第一行,即:-

@model WebApplication2.Models.CustomerViewModel

因此您的视图是强类型视图,其模型定义为CustomerViewModel。在您的操作方法中接受CustomerViewModel,然后创建一个新的Customer对象,并使用CustomerViewModel的属性填充其属性,例如:-

[HttpPost]
public ActionResult Create(CustomerViewModel customerViewModel) 
{
    Customer customer = new Customer
    {
        //make customers properties = customerviewmodels properties
        customerName = customerViewModel.customerName        //etc
    };
    context.Customer.Add(customer);
    context.SaveChanges();
    return RedirectToAction("Index", "Customer");
}