问题描述
我有一个组件视图,我尝试从其中的表单更新数据,我调用了控制器,但在控制器中我收到了 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();
}
它应该可以工作,我不知道为什么它不断向我的控制器发送空值。
解决方法
你可以在浏览器中按F12查看html元素,你会发现这些元素的名字是这样的:model.Bedrooms
。因为你的主模型是CustomerPropertyModelView
,但你的输入属于{{1在TblCustomerProperty
中命名为model
的}}。如果你的后端代码收到CustomerPropertyModelView
作为参数,它不会为空。但如果你收到CustomerPropertyModelView
作为参数,你需要指定后缀。
更改如下:
TblCustomerProperty