MVC5提交后文本框中的值丢失 [英] MVC5 Lost value in Textbox after Submit

查看:117
本文介绍了MVC5提交后文本框中的值丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想澄清有关MVC5剃刀视图的一件事.

I would like to clarify one thing about MVC5 Razor Views.

有人告诉我,我不必在剃须刀视图中使用HTML Helpers(@ Html.EditorFor,@ Html.TextBoxFor),它仍然可以使用.

I was told that I don't have to use HTML Helpers (@Html.EditorFor, @Html.TextBoxFor) in my razor views and it will still work.

控制器代码

[HttpPost]
        public ActionResult Create(Models.TestObj obj)
        {
            ViewBag.TestStr = string.Format("You typed: {0} {1}", obj.FirstName, obj.LastName);
            return View(obj);
        }

剃刀视图

@using (Html.BeginForm())
{

        <div>
            @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control", style = "width: 120px;" } })     
            <input class="form-control text-box single-line" id="LastName" name="LastName" style="width: 120px;" type="text">       
            <input type="submit" name="submit" value="Filter" / >
        </div>


    @ViewBag.TestStr
}

但是当我像上面那样实际测试时,不会保留在"LastName"文本框中键入的值.我可以在Controller中捕获两个文本框值.但是回发后,丢失了"LastName"文本框中的值.使用HTMLHelper创建的文本框虽然没有丢失值.

But when I actually test it like the above, the value typed in 'LastName' textbox is not preserved. I can catch both textbox values in my Controller. But after postback, lost the value in 'LastName' textbox. The textbox which is created by using HTMLHelper didn't lose the value though.

我做错什么了吗?或者应该是那样吗?如果要保留提交的值,是否必须在MVC5的RazorViews中使用HtmlHelpers?

Am I doing something wrong or is it supposed to be like that? Do I have to use HtmlHelpers in RazorViews in MVC5 if I want to keep the submitted values?

推荐答案

您没有将第二个输入绑定到LastName的值,只是设置了它的name属性.如果检查生成的html,您会注意到第一个具有value属性,而第二个则没有.

Your not binding the second input to the value of LastName, just setting its name attribute. If you inspect the html you generating, you will note the first one has a value attribute whereas the second does not.

您需要像使用FirstName一样使用EditorFor()(或TextBoxFor()),FirstName会生成正确的value属性(以及其他使用客户端验证所需的data-val-*属性).

You need to use the EditorFor() (or TextBoxFor()) as you did for the FirstName which generates the correct value attribute (and other data-val-* attributes necessary for using client side validation).

旁注:您也可以使用

<input name="LastName" ..... value="@Model.LastName"` />

但是这不会考虑ModelState

这篇关于MVC5提交后文本框中的值丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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