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

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

问题描述

我将模型切回了一个领域:

I have cut the model back to one field:

//型号

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

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

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.

推荐答案

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

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天全站免登陆