【问题标题】:ModelBinder returns null for one particular ViewModelModelBinder 为一个特定的 ViewModel 返回 null
【发布时间】:2017-05-25 23:54:27
【问题描述】:

我知道,有很多问题,尝试了解决方案,但都没有奏效。基本上,我被卡住了……

ViewModel:
public class CreateStrengthViewModel
{
    public string Strength { get; set; }
    public IEnumerable<Categories.CategoryViewModel> Categories { get; set; }
    public int Category { get; set; }
}

Post:
-----------------------------7e01e1381a08c2
Content-Disposition: form-data; name="__RequestVerificationToken"
iErDomlK5vCWAFFMlGkb2-HgLCoquxfeIlYeI3pmrsW_5VSD8-huS6JbCdA4OAg4s8nMgqKAHPHArVoQ3GzfFWf2I-Yx6iWgvkWRNI6jiKA1
-----------------------------7e01e1381a08c2
Content-Disposition: form-data; name="Strength"
FMC Extra
-----------------------------7e01e1381a08c2
Content-Disposition: form-data; name="Category"
1
-----------------------------7e01e1381a08c2--

Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(
    [Bind(Include = "Strength,Category")]
    CreateStrengthViewModel strength)
    {
        using (StrengthServices service = new StrengthServices(new ImperialTobacco_Database()))
        {
            //service.CreateAndSave(strength);
            ...
        }
    }
}

无论我在做什么,控制器方法内部的力量都是空的。如您所见,浏览器发送数据,但 ModelBinder 不会做任何事情。哦,顺便说一句:相同的代码适用于具有不同 Include 字段的不同 ViewModel。是的,我已经尝试移除 Bind,或者只绑定其中一个传入的变量,没有任何变化。

有趣的是;这是有效的:

public class CreateCompanyViewModel
{
    public string Name { get; set; }
    public string Color { get; set; }

    public IEnumerable<MarketViewModel> MarketsOfOperations { get; set; }
    public IEnumerable<int> SelectedOperations { get; set; }
}

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Name,Color,SelectedOperations")] CreateCompanyViewModel company)
    {
        using (CompanyServices service = new CompanyServices(new ImperialTobacco_Database()))
        {
            service.CreateAndSave(company);
            return RedirectToAction("Index", "Management");
        }
    }

老实说,我不知道发生了什么以及为什么 ModelBinder 从发布的数据中什么也得不到,尤其是在几乎完全相同的数据完美运行的情况下。

P.S.:我再次尝试更改属性和绑定名称,但没有成功。

【问题讨论】:

标签: c# asp.net-mvc-5 model-binding


【解决方案1】:

问题是您的模型中的属性名称与您的操作方法中的参数名称相匹配。

因此,如果您从

更改操作名称参数
public ActionResult Create([Bind(Include = "Strength,Category")]  CreateStrengthViewModel strength)

到

public ActionResult Create([Bind(Include = "Strength,Category")]  CreateStrengthViewModel strengthModel)

这样就解决了

【讨论】:

  • 小到看不出来的问题。像魅力一样工作,谢谢。
猜你喜欢
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 2020-09-13
  • 2020-06-18
相关资源
最近更新 更多