选中复选框时,ASP.NET MVC更改数据库值

时间:2017-09-26 13:06:01

标签: c# asp.net-mvc entity-framework razor

我有一个非常简单的问题。我有一个表单,如果您选中复选框并提交表单,则会将值更改为true(默认情况下为“false”)。目前它对我不起作用。所以我问我应该怎么做?

以下是我如何做的一些事情。有一个值" IsConfirmed"

public virtual bool IsConfirmed {get;set;}

我有一个简单的HttpPost方法。

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit([Bind(Include = "UserName,Id,Email")] ApplicationUser formuser, string id, string RoleId)
    {
        var role = new ApplicationUser() { Id = formuser.Id, Email = formuser.Email, IsConfirmed = formuser.IsConfirmed };
        await UserManager.UpdateAsync(role);
        return RedirectToAction("Index");
    }

这是我的观点

@model CPO.Models.ApplicationUser
@{
ViewBag.Title = "Edit";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
@Html.HiddenFor(model => model.Id)

<table class="table table-bordered table-hover">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.UserName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
    </tr>
        <tr>
            <td>
                @Html.HiddenFor(model => model.Email)
                @Html.DisplayFor(model => model.Email)
               @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
            </td>
            <td>
                @Html.HiddenFor(model => model.UserName)
                @Html.DisplayFor(model => model.UserName)
                @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
            </td>
            <td>
                @Html.HiddenFor(model => model.FirstName)
                @Html.DisplayFor(model => model.FirstName)
            </td>
            <td>
                @Html.HiddenFor(model => model.LastName)
                @Html.DisplayFor(model => model.LastName)
            </td>
            <td>
                @Html.DropDownList("RoleId", "Select Role")
            </td>
            <td>
                @Html.EditorFor(model => model.IsConfirmed)
            </td>
            <td>
                <input type="submit" value="Edit" class="btn btn-default"/>
            </td>
        </tr>
</table>
}
@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

}

很奇怪,但它不起作用,我不知道为什么,也许我错过了定义的东西,但模型的价值是假的,即使它被检查了。

任何帮助都非常感谢,如果我犯了错误,请善意写,我在评论中写了它们并且我会修复它们

1 个答案:

答案 0 :(得分:2)

您已使用IsConfirmed

BindAttribute属性排除在绑定之外
[Bind(Include = "UserName,Id,Email")]

表示仅绑定属性UserNameIdEmail

的值

删除属性,或将其更改为包含属性

[Bind(Include = "UserName, Id, Email, IsConfirmed")]

另请注意,您已从绑定中排除了属性FirstNameLastNameRoleId,因此几乎没有任何内容包括表单控件