0

我有一个组件视图,我尝试从其中的表单更新数据,我调用控制器但在控制器中我收到 null :

 public class CustomerPropertyViewComponent: ViewComponent
    {
        private MyDBContext context;
        public CustomerPropertyViewComponent(MyDBContext _contex)
        {
            context = _contex;
        }

        public async Task<IViewComponentResult> InvokeAsync(int id)
        {

            CustomerPropertyModelView c = new CustomerPropertyModelView();
            TblCustomerProperty t = new TblCustomerProperty(context);
            c = t.getAllInfo(id);
            if (c.model == null)
            {
                c.model = new TblCustomerProperty();
                c.model.CustomerId = id;
            }
            return View(c);
        }
    }

在我看来

@model SunSystemDotNetCoreVersion.Models.helpers.CustomerPropertyModelView
    
<form asp-action="Update" asp-controller="CustomerProperties"
          data-ajax="true"         
          data-ajax-method="POST"
          method="post">

        <div class="row w-100">
            <div class="col-6">
                <div class="row align-items-center h-100">
                    <div class="col-5 text-right">
                        Number of Bedrooms
                    </div>
                    <div class="col-7 p-1 p-1">
                        @Html.TextBoxFor(model => model.model.Bedrooms, new { @class = "form-control", Type = "number" })
                    </div>
                    <div class="col-5 text-right">
                        Current Heating System
                    </div>
                    <div class="col-7 p-1">
                        <select asp-for="model.HeatingSystemTypeId" class="form-control"
                                asp-items="@(new SelectList(Model.HeatingsList,"HeatingSystemTypeId","Title"))">
                            <option value="0">-Plaese Select-</option>
                        </select>
                    </div>
                   .....

            <div class="col-12">
                <button type="submit" >Save</button>
            </div>
        </div>

    </form>

我已经减少了大部分视图代码,但它包含了模型需要的所有数据。这是我的控制器:

 public class CustomerPropertiesController : Controller
        {
            private readonly MyDBContext_context;
    
            public CustomerPropertiesController(MyDBContextcontext)
            {
                _context = context;
            }
    
               public IActionResult Update(TblCustomerProperty modelView) {
                //here modelView is null
                return View();
            }

它应该可以工作我不知道为什么它一直向我的控制器发送 null 。

4

1 回答 1

1

model.Bedrooms你可以F12查看浏览CustomerPropertyModelView器中的html元素,你会发现这些元素的名字是TblCustomerProperty这样model的null。但如果你作为参数接收,你需要指定后缀。CustomerPropertyModelViewCustomerPropertyModelViewTblCustomerProperty

更改如下:

public IActionResult Update([Bind(Prefix ="model")]TblCustomerProperty modelView)
{
    return View();
}
于 2021-04-01T03:15:45.743 回答