指定名称的MVC TextBox在发布时未绑定模型 [英] MVC TextBox with name specified not binding model on post

查看:90
本文介绍了指定名称的MVC TextBox在发布时未绑定模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就像这里的MVC 101,所以我对为什么它不起作用感到完全无奈.我有一个非常基本的模型:

This is like MVC 101 here so I feel completely helpless on why this isn't working. I have an extremely basic Model:

public class StockEnrollmentModel
{
    [Required]
    [DisplayName("Employee Name:")]
    public string EmployeeName { get; set; }

}

我的视图如下:

@using (Html.BeginForm("SimulateForm", "HR", FormMethod.Post))
{
<div class="row">
    <div class="col-md-6">
        <div class="form-group">
            @Html.LabelFor(e => e.EmployeeName)
            @Html.TextBox("stock_employee_name", Model.EmployeeName)
        </div>
    </div>
</div>
<button type="submit" class="btn btn-primary" value="Submit">Submit</button>
}

我要发布到的Web服务要求输入字段具有特定名称,以便成功接收数据

在此情况下,呈现的html需要阅读:

<input type="stock_employee_name" type="text" /> 

经过大量的搜索后,我确定需要使用Html.Text框来控制所生成的name属性.

After much googling, I determined I need to use an Html.Text box in order to have control of the name attribute that is generated.

我遇到的问题是,当我提交表单时,控制器中的模型完全没有数据.调查这表明表单以"employee_stock_name =某些名称"而不是"EmployeeName =某些名称"发布到服务器上

The problem I'm having is that when I submit the form, the model in my controller is completely void of data. Investigating this shows that the form posted to the server with "employee_stock_name=Some Name" rather than "EmployeeName=Some Name"

根据我的研究,这不应该发生,对吗?这种确切的情况应该是您使用TextBox而不是TextBoxFor的原因.

From my research, this shouldnt be happening, correct?? This exact situation should be the reason you use TextBox instead of TextBoxFor.

我想念什么?

这是我的价值控制者:

[HttpPost]
    public RedirectToRouteResult SimulateForm(StockEnrollmentModel model )
    {
        if ( ModelState.IsValid )
        {
            return RedirectToAction("SignForm", "HR", model);
        }
        return RedirectToAction("StockPurchase", model );
    }

更新

下面接受的答案是我最终使用的答案.没有真正的方法可以轻松地更改HTML字段的名称并维护MVC模型绑定.我最终更改了属性名称,以匹配需要读取的名称字段.

The accepted answer below was what I eventually ended up using. There's no real way to easily change the name of the HTML field and maintain the MVC model binding. I ended up changing my property names to match what I needed the name field to read.

推荐答案

The first parameter of the HtmlHelper.TextBox function is the name attribute of the input element created by the function. You're specifying "employee_stock_name" as that parameter (and thus as the name attribute of the input element), so that is what is being sent across the wire.

您应该指定正确的名称:

You should either specify the correct name:

@Html.TextBox("EmployeeName", Model.EmployeeName)

或使用HtmlHelper.TextBoxFor自动生成它:

@Html.TextBoxFor(m => m.EmployeeName)

这篇关于指定名称的MVC TextBox在发布时未绑定模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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