MVC中如何在edit.cshtml页面禁用指定文本框?
在MVC的Edit页面禁用Eno文本框的解决方案
要禁用Edit页面中Eno对应的文本框,有两种常用实现方式,同时需要注意表单提交时的值传递问题:
方式一:直接添加disabled属性
在EditorFor的htmlAttributes中加入@disabled = "disabled",即可禁用文本框。但要注意:被disabled的表单控件不会提交值到后端,所以需要确保后端能正确获取Eno的值(比如从路由参数id中获取)。
修改后的Edit.cshtml代码:
<div class="form-group"> @Html.LabelFor(model => model.Eno, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Eno, new { htmlAttributes = new { @class = "form-control", @disabled = "disabled" } }) @Html.ValidationMessageFor(model => model.Eno, "", new { @class = "text-danger" }) </div> </div>
对应后端Post方法可调整为从路由获取id(需确保路由中包含id参数):
[HttpPost] public ActionResult Edit(int id, Models.Employee e1) { // 用id作为Eno的值 e1.Eno = id; int i = objdalemp.UpdateEmployee(e1); if(i==1) { return RedirectToAction("Index"); } return View(e1); }
方式二:使用readonly+保留字段提交(无需修改后端)
如果需要文本框不可编辑但仍能正常提交Eno的值,可以用readonly属性替代disabled:
修改后的Edit.cshtml代码:
<div class="form-group"> @Html.LabelFor(model => model.Eno, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Eno, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } }) @Html.ValidationMessageFor(model => model.Eno, "", new { @class = "text-danger" }) </div> </div>
这种方式下,文本框无法编辑,且表单提交时Eno的值会正常传递到后端,无需修改原有的Post方法。
内容的提问来源于stack exchange,提问作者Nani
相关产品推荐
相关产品推荐

