简体   繁体   English

活页夹困境

[英]Model binder woes

why do I always have so much trouble with the model binder?? 为什么我总是对模型活页夹有太多麻烦? I have the following controller: 我有以下控制器:

namespace X.Web.Controllers
{
    public class ExpertsVM
    {
        public string GivenName;
        public string Surname;
    }

    public class AuthController : Controller
    {
        [HttpPost]
        public ActionResult RegisterExpert(ExpertsVM v)
        {

and my view looks like this: 我的看法如下所示:

@using X.Web.Controllers
@model ExpertsVM

@using (Html.BeginForm("RegisterExpert", "Auth"))
{
    @Html.EditorFor(x => x.GivenName)
    @Html.EditorFor(x => x.Surname)

so the form gets rendered like this: 因此,表单的呈现方式如下:

<form action="/Auth/RegisterExpert" method="post">
<input class="text-box single-line" id="GivenName" name="GivenName" type="text" value="" />
<input class="text-box single-line" id="Surname" name="Surname" type="text" value="" />

but when the action gets invoked, v contains all nulls. 但是当操作被调用时, v包含所有空值。 if I declare the action like this: 如果我这样声明动作:

[HttpPost]
public ActionResult RegisterExpert(FormCollection f)
{

I see all the values... so what am I doing wrong here? 我看到了所有的价值...所以我在这里做错了什么?

I'm not 100% sure but I would use property instead of public field. 我不确定100%,但是我会使用属性而不是公共领域。

try 尝试

public class ExpertsVM
{
    public string GivenName {get;set;}
    public string Surname {get;set;}
}

The model binder looks for public properties on the model. 模型绑定程序在模型上查找公共属性。 VdesmedT's answer is right, but I am adding this to add emphasis to the point (he wasn't 100% sure, I am). VdesmedT的答案是正确的,但是我添加这个来强调这一点(我不是100%肯定的)。

You could also spare yourself one of the using statments by doing: 您还可以通过执行以下操作来避免使用其中之一:

@model X.Web.Controllers.ExpertsVM

I have upvoted VdesmedT's answser. 我对VdesmedT的答案表示反对。 You should mark that as the answer. 您应该将其标记为答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM