c# – 控制器后期操作不接收模型

非常基本的型号:

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();
   }
}

加载屏幕时,值正确绑定到页面.但是当我按下提交按钮时,person对象具有age和amp;的所有空值.名称.

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

我在Html.BeginForm()的调用中错过了什么?

解决方法

您必须在模型中创建属性

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仅绑定属性.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...