在MVC3中编辑页面时Get的参数名与Post里的Model参数一致时不需要在View页面再绑定参数

 //get 更改密码
        public ActionResult ResetPassword(Guid? userid)
        {
            var item = _db.Users.Find(userid);
            return View(item);
        }

        [HttpPost]
        public ActionResult ResetPassword(Proweb.Models.User user)
        {
            try
            {
                var item = _db.Users.Single(u => u.UserId.Equals(user.UserId));
                item.Password = (user.UserId + user.Password).GetMD5();
                _db.Entry(item).State = EntityState.Modified;
                _db.SaveChanges();
                return View("Close");
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMsg = "发生错误了!错误信息为:" + ex.Message;
                return View("Error");
            }

        }

在View页面里不需要绑定UserId

@model User

@{
    Layout = "~/Areas/Mana/Views/Shared/_Layout_detail.cshtml";
}
@using (Html.BeginForm())
{
    <fieldset>
    <legend>初始化密码</legend>
    <table id="table-detail" cellpadding="2px">
      <tr>
        <th>@Html.LabelFor(modelitem => modelitem.RealName)</th>
        <td>@Html.TextBoxFor(model => model.RealName, new { readOnly = "readOnly", style = "background-color: #EFEFEF;padding: 2px;" }) 不允许编辑  @Html.ValidationMessageFor(model => model.RealName)</td>
      </tr>
      <tr>
        <th>@Html.LabelFor(modelitem => modelitem.UserAccount )</th>
        <td>@Html.TextBoxFor(model => model.UserAccount, new { readOnly = "readOnly", style = "background-color: #EFEFEF;padding: 2px;" }) 不允许编辑  @Html.ValidationMessageFor(model => model.UserAccount)</td>
      </tr>
      <tr>
        <th>@Html.LabelFor(model => model.Password)</th>
        <td>@Html.TextBoxFor(model => model.Password, new { Value = "",type="password" }) @Html.ValidationMessageFor(model => model.Password)</td>
      </tr>
      <tr align="center"><td colspan="2"><input type="submit" value="保存" class="ui-state-default button2pointer"/>    <input type="reset" value="重置" class="ui-state-default button2pointer"/></td></tr>
    </table>
    </fieldset> 
} 

如果在 ResetPassword(Guid? userid)这里的参数“userid”如果更换成:id那么在View页面就要隐藏绑定Userid不然Post时会出错。
就是说要在View里加上:@Html.HiddenFor(item=>item.UserId)

学习交流群:364976091
上一篇:支持stl容器的gdb自定义命令


下一篇:比较不同的 PaaS 平台上的 Node.js 支持