html.hiddenfor for disabled dropdownlist,默认值为MVC

时间:2018-04-30 16:54:45

标签: c# asp.net-mvc

我编辑了de Create视图以添加隐藏的字段控件,但我无法获得值

<div class="form-group">
   @Html.LabelFor(model => model.EmpresaId, "Empresa", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("EmpresaId", null, htmlAttributes: new { @class = "form-control", @disabled = "disabled" })
            @Html.HiddenFor(model => model.EmpresaId)
            @Html.ValidationMessageFor(model => model.EmpresaId, "", new { @class = "text-danger" })
        </div>
</div>

创建的html是:

    <div class="form-group">
        <label class="control-label col-md-2" for="EmpresaId">Empresa</label>
        <div class="col-md-10">
            <select class="form-control" disabled="disabled" id="EmpresaId" name="EmpresaId">
              <option selected="selected" value="1">Farmacia MZ</option>
              <option value="2">Credesa</option>
            </select>
            <input length="19" id="EmpresaId" name="EmpresaId" type="hidden" value="">
            <span class="field-validation-valid text-danger" data-valmsg-for="EmpresaId" data-valmsg-replace="true"></span>
        </div>
    </div>

正如您所见,隐藏的输入没有任何价值。

On Controller是DropDownList默认值设置:

public ActionResult Create()
    {
        ApplicationUser usr = db.Users.Find(User.Identity.GetUserId().ToString());
        int userId = (int)usr.EmpresaId;
        ViewBag.CategoriaId = new SelectList(db.Categorias, "CategoriaId", "Nombre");
        ViewBag.EmpresaId = new SelectList(db.Empresas, "EmpresaId", "Nombre", userId); <-- defalut value for disabled DropDownList
        ViewBag.MarcaId = new SelectList(db.Marcas, "MarcaId", "Nombre");
        return View();
    }

我搜索了很多,但我不明白错误是什么。帮助很好!

1 个答案:

答案 0 :(得分:0)

这个HiddenFor帮助器明确地绑定到EmpresaId viewmodel属性:

@Html.HiddenFor(model => model.EmpresaId)

隐藏字段值具有空白值,因为它未从GET操作方法中的相应viewmodel属性分配,因为您实际上已将EmpresaId的默认值分配给ViewBag.EmpresaId,其中包含{{1} }}

SelectList

因此,您需要创建一个viewmodel实例,然后将默认值分配给viewmodel属性并返回到GET操作方法中的视图:

ViewBag.EmpresaId = new SelectList(db.Empresas, "EmpresaId", "Nombre", userId);

或者只是在viewmodel实例创建过程中设置默认值:

// create new instance of viewmodel and set default property value
var model = new ViewModel();
model.EmpresaId = userId;

// return default values from viewmodel to view page
return View(model);

作为旁注,请始终使用强类型var model = new ViewModel() { EmpresaId = userId; }; return View(model); 帮助程序而不是DropDownListFor来绑定viewmodel属性:

DropDownList