Asp.net core mvc 在.net核心MVC中将表单数据从视图组件传递到控制器
我有一个组件视图,我尝试从其中的一个表单更新数据,我调用控制器,但在控制器中我收到null:Asp.net core mvc 在.net核心MVC中将表单数据从视图组件传递到控制器,asp.net-core-mvc,view-components,Asp.net Core Mvc,View Components,我有一个组件视图,我尝试从其中的一个表单更新数据,我调用控制器,但在控制器中我收到null: public class CustomerPropertyViewComponent: ViewComponent { private MyDBContext context; public CustomerPropertyViewComponent(MyDBContext _contex) { context = _co
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);
}
}
我不知道为什么它一直向我的控制器发送null。你可以F12检查浏览器中的html元素,您会发现这些元素的名称如下:
model.beddooms
。因为您的主模型是CustomerPropertyModelView
,但您的输入属于TblCustomerProperty
,它在CustomerPropertyModelView
中命名为model
。如果您的后端代码收到CustomerPropertyModelView
作为参数,它将不为空。但是如果您接收TblCustomerProperty
作为参数,则需要指定后缀
更改如下:
public IActionResult Update([Bind(Prefix ="model")]TblCustomerProperty modelView)
{
return View();
}
您确定
modelView
为null
?这听起来很奇怪,对于复杂类型的模型绑定,即使模型绑定失败,也始终会创建默认实例。因此,模型的属性可以为null,但模型本身不应为null。顺便说一句,从您的代码来看,传入的视图模型应该是Update
CustomerPropertyModelView而不是TblCustomerProperty
。如果您实际上指的是TblCustomerProperty
,则视图代码是错误的。但是您仍然应该确认modelView
是否为null
或者只是它的属性。@KingKing modelView及其所有属性都为null。我想这是因为命名的原因,我会尝试丽娜的建议。谢谢你的回复,我尝试了一下,并让你知道结果。谢谢,亲爱的@rena。这是获取我的ModelView(TblCustomerProperty)的一个字段的工作。事实上,我的ModelView还有一些其他属性,我无法通过后缀读取,但我可以使用TblCustomerProperty:)
public class CustomerPropertiesController : Controller
{
private readonly MyDBContext_context;
public CustomerPropertiesController(MyDBContextcontext)
{
_context = context;
}
public IActionResult Update(TblCustomerProperty modelView) {
//here modelView is null
return View();
}
public IActionResult Update([Bind(Prefix ="model")]TblCustomerProperty modelView)
{
return View();
}