当我回发到我的控制器时,我的模型的所有值都为空 [英] When I post back to my controller all values for my model are null

查看:22
本文介绍了当我回发到我的控制器时,我的模型的所有值都为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将模型切回一个字段:

//模型

公共类LetterViewModel{公共字符串 LetterText;}

//控制器

public ActionResult Index(){var model = new LetterViewModel();model.LetterText = "任何东西";返回视图(模型);}[HttpPost]公共 ActionResult 索引(LetterViewModel 模型){//model.LetterText == null返回视图(模型);}

//查看

@model Test.Models.LetterViewModel@{布局 = "~/Views/Shared/_Layout.cshtml";ViewBag.Title = "创建一封信";}@using (Html.BeginForm()){<div id="底部">@Html.TextAreaFor(m => m.LetterText)<input type="submit" value="Ok" class="btn btn-default"/>

}

当我检查开发工具中的网络选项卡时,它显示输入的值包含在请求中.但是,当 HttpPost 控制器被触发时,该字段为空.

解决方案

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

公共类LetterViewModel{公共字符串 LetterText { 获取;放;}//添加getter/setter}

I have cut the model back to one field:

//Model

public class LetterViewModel
{
    public string LetterText;
}

//Controller

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

//view

@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>
}

When I check the Network tab in dev tools it is showing the value entered is being included in the request. However, when the HttpPost controller is fired the field is empty.

解决方案

The DefaultModelBinder does not set the value of fields, only properties. You need to change you model to include properties

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

这篇关于当我回发到我的控制器时,我的模型的所有值都为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆