如何使用Entity框架MVC5从数据库传递值隐藏字段

时间:2016-07-14 14:43:27

标签: asp.net-mvc entity-framework

我正在使用MVC实体框架我已生成代码我有字段Isactive此字段的值为true或false。代码看起来像

控制器:

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="ClientId,ClientName,PrimaryContactName,EmailId,PrimaryContact,IsActive,ModifiedBy,ParentCompany")] TP_InternalClients tP_InternalClients)
        {
            if (ModelState.IsValid)
            {
                db.Entry(tP_InternalClients).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(tP_InternalClients);
        }

模型:

 public class InternalClients
    {
        public int ClientId { get; set; }
        public string ClientName { get; set; }
        public string PrimaryContactName { get; set; }
        public string EmailID { get; set; }
        public string PrimaryContact { get; set; }
        public bool IsActive { get; set; }
        public string ModifiedBy { get; set; }
        public int ParentCompany { get; set; }
    }

查看:

 <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.IsActive)
                    @Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger" })
                </div>
            </div>

运行代码后Isactive下拉显示true或false我希望隐藏字段,该时间发送值默认为true仅对数据库。我怎么能隐藏和发送默认值?我正在做我的错误

1 个答案:

答案 0 :(得分:1)

在您的表单中,只需替换

即可
<div class="checkbox">
     @Html.EditorFor(model => model.IsActive)
     @Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger" })
</div>

<input type="hidden" name="IsActive" value="true" />

或者您可以使用Html辅助方法

@Html.HiddenFor(s=>s.IsActive)

现在确保在GET操作中将默认值设置为您想要的任何值。

但是,如果要保存默认值,请在HttpPost操作中执行,不需要在表单中保留隐藏字段(用户可以使用浏览器开发更新隐藏字段值工具)

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="ClientId,ClientName,PrimaryContactName,EmailId,
                       PrimaryContact,ModifiedBy,ParentCompany")] TP_InternalClients model)
{
        if (ModelState.IsValid)
        {
            model.IsAcive = true ; 
            db.Entry(model).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(tP_InternalClients);
}

请记住,the best way to prevent overposting is to use a view model with only those properties needed for the view