0

我正在使用 ASP.NET MVC,但在使用 CheckBoxFor 时遇到了一些问题。这是我的问题:

我在视图中有以下代码:

@Html.CheckBoxFor(model => model.stade, new { @id = "stade" })

model.stade是布尔类型。在我的控制器中,我有:

//Editar
[HttpPost]
public ActionResult InvoiceType(int Id, string Name, string Code, string Stade)
{
    clsInvoiceTypea Model = new clsInvoiceType();
    Model.Id = Id;
    Model.Name = Name;
    Model.Code = Code;
    Model.Stade = stade== "1" ? true : false;
    return PartialView(Model);
}

我收到一个错误,因为当Model.Stade提交给视图时,值是 1 或 0,并且我收到一个错误说“无法将字符串识别为有效的布尔值”,但是如果 Model.stade 是布尔值,为什么模型被提交给像0或1这样的视图?我该如何解决这个问题?

4

1 回答 1

2

这是我的解决方案 -

让您的模型成为 -

public class clsInvoiceTypea
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Code { get; set; }
        public bool stade { get; set; }
    }

让您的 HttpGet 操作成为 -

public ActionResult GetInvoice()
{
    clsInvoiceTypea type = new clsInvoiceTypea();
    return View(type);
}

以及相应的视图——

@model YourValidNameSpace.clsInvoiceTypea

@{
    ViewBag.Title = "GetInvoice";
}

<h2>GetInvoice</h2>

@using (Html.BeginForm("SubmitData","Home",FormMethod.Post)) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>clsInvoiceTypea</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Code)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Code)
            @Html.ValidationMessageFor(model => model.Code)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.stade)
        </div>
        <div class="editor-field">
            @Html.CheckBoxFor(model => model.stade)
            @Html.ValidationMessageFor(model => model.stade)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

让以下成为您的 HttpPost 操作 -

[HttpPost]
public ActionResult SubmitData(clsInvoiceTypea model)
{
    return View();
}

运行代码时,您将获得以下视图 -

在此处输入图像描述

当您选中复选框并点击创建按钮时,如果您在 POST 方法上放置断点并检查值,您将得到 true。

在此处输入图像描述

于 2014-10-04T07:09:56.870 回答