【问题标题】:controller post action doesn't receive model控制器发布操作未收到模型
【发布时间】:2013-01-07 07:50:33
【问题描述】:

非常基本的模型:

public class Person
{
    public string Name;
    public int Age;
}

和非常简单的视图:

@model DynWebPOC.Models.Person

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Hello, @Model.Name
<br/>
You're getting old at @Model.Age years old now!

@using(Html.BeginForm("Index","Test",FormMethod.Post))
{
    <fieldset>       
        <label for="name" style="color: whitesmoke">Name:</label>    
        @Html.TextBoxFor(m => m.Name)
        <br/>
        <label for="age" style="color: whitesmoke">Age:</label>

        @Html.TextBoxFor(m => m.Age)

        <br/>
        <input type="submit" value="Submit"/>
    </fieldset>
}

还有一个非常简单的控制器:

public class TestController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        object model = new Person {Name = "foo", Age = 44};
        return View(model);
    }


   [HttpPost]
   public ActionResult Index(Person person)
   {
       return View();
   }
}

当屏幕加载时,值会正确绑定到页面。但是当我按下提交按钮时,人对象的年龄和姓名都为空值。

因为我使用了 Html.TextBoxFor,它不应该正确设置所有绑定并且对象应该自动绑定回 POST 吗?它在 GET 中绑定得很好..

我在调用 Html.BeginForm() 时是否遗漏了什么?

【问题讨论】:

  • 你试过EditorFor而不是TextBoxFor吗?
  • 另外,调试 post 方法时检查 Request.Form 里面的内容
  • 设置为 EditorFor 在我尝试仅加载页面行时在第 3 行给出未处理的 NullReferenceException =( Type tModel = ViewData.ModelMetadata.ContainerType.GetProperty(ViewData.ModelMetadata.PropertyName).PropertyType;)
  • 打开源视图并在页面中查找具有 id 或名称“姓名”和“年龄”的其他输入。有时你不小心有其他同名的输入,而 MVC 无法绑定,因为请求创建了一个包含这些值的集合。
  • 我刚刚检查过,没有重复的输入标签。我确实发布了所有代码,我只是想让一个简单的示例正常工作

标签: c# asp.net-mvc razor


【解决方案1】:

您必须在模型中创建属性

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

而不是

public class Person
{
    public string Name;
    public int Age;
}

ASP.net MVC 只绑定属性。

【讨论】:

    【解决方案2】:

    为什么您的模型在Get 方法中是object?这可能是混淆模型绑定器的原因。这也看起来像为什么当您将它们更改为 EditorFors 时它会在页面加载时引发异常

    尝试强输入:

    [HttpGet]
    public ActionResult Index()
    {
        Person model = new Person {Name = "foo", Age = 44};
        return View(model);
    }
    

    【讨论】:

    • 我刚刚更改了它,但它仍然给出了 EditorFor 的异常。使用 TextBoxFor,它仍然没有绑定到 POST。不过,它确实绑定了 GET 上的向下页面,所以我认为从对象更改为 Person 并不重要
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多