C# 当我发回控制器时,我的模型的所有值都为空

C# 当我发回控制器时,我的模型的所有值都为空,c#,asp.net-mvc,C#,Asp.net Mvc,我已将模型缩减为一个字段: //模型 public class LetterViewModel { public string LetterText; } //控制器 public ActionResult Index() { var model = new LetterViewModel(); model.LetterText = "Anything"; return View(model); } [HttpPost] public ActionResul

我已将模型缩减为一个字段:

//模型

public class LetterViewModel
{
    public string LetterText;
}
//控制器

public ActionResult Index()
{
    var model = new LetterViewModel();
    model.LetterText = "Anything";

    return View(model);
}

[HttpPost]
public ActionResult Index(LetterViewModel model)
{ 
    //model.LetterText == null
    return View(model);
}
//看法

@model Test.Models.LetterViewModel
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Create a Letter";
}
@using (Html.BeginForm())
{
    <div id="Bottom">
        @Html.TextAreaFor(m => m.LetterText)
        <input type="submit" value="Ok" class="btn btn-default" />
    </div>
}
@model Test.Models.LetterViewModel
@{
Layout=“~/Views/Shared/_Layout.cshtml”;
ViewBag.Title=“创建一封信”;
}
@使用(Html.BeginForm())
{
@Html.TextAreaFor(m=>m.lettext)
}

当我检查dev tools中的Network选项卡时,它显示输入的值包含在请求中。但是,当触发HttpPost控制器时,该字段为空。

DefaultModelBinder不设置字段值,仅设置属性。您需要更改模型以包含属性

public class LetterViewModel
{
    public string LetterText { get; set; } // add getter/setter
}

如果您没有将字段转换为属性的选项,也可以使用自定义活页夹而不是默认活页夹

循环表单输入,并使用反射设置它们
MemberInformation
是我的类,但您可以使用
FieldInfo

这不做对象图,但如果我需要这种能力,我会提高我的答案。
foreach
中的元组使用c#7.0。它还假设您保存了此
POST
之前的
GET
中的对象

using CommonBusinessModel.Metadata;
using GHCOMvc.Controllers;
using System;
using System.Linq;
using System.Web.Mvc;

namespace AtlasMvcWebsite.Binders
{
  public class FieldModelBinder : DefaultModelBinder
  {
    // this runs before any filters (except auth filters)
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
      var form = controllerContext.HttpContext.Request.Form;
      Type type = typeof(GHCOBusinessModel.GHCOPPAType);
      AtlasKernelBusinessModel.VersionedObject instance = PolicyController.Policy;

      foreach ((var value, var member) in (from string input in form
                                           let fi = type.GetField(input)
                                           where fi != null
                                           let mi = new MemberInformation(fi, instance)
                                           where !mi.ReadOnly
                                           select (form[input], mi)))
        member.SetValue(value);

      return instance;
    }

  }
}
您需要在参数之前向操作添加[FromBody]


您在post methods parameter(即模型)中得到了什么?您能解释一下您的意思吗?只需调试您的post方法,post methods参数中有什么值?它是空的吗?当我在字段中键入“Test”并提交表单时,我可以看到dev tools中的请求对象包含letterxt:Test,但是当我在HttpPost控制器的代码上设置断点时,我得到model.LetterText=null。在begin表单中用post请求提及操作和控制器名称,然后重试。谢谢,这就是我需要的答案。
[HttpPost]
public ActionResult Index([FromBody]LetterViewModel model)
{ 
    //model.LetterText == null
    return View(model);
}