有没有办法将复选框列表绑定到 asp.net mvc 中的模型

发布于 2024-10-15 14:52:20 字数 393 浏览 1 评论 0原文

我在这里寻找一种快速、简单的方法来在模型中发生回发时绑定复选框列表项的列表。

显然,现在常见的做法似乎是这样做的 form.GetValues("checkboxList")[0].Contains("true"); 这看起来很痛苦而且不完全安全。

有没有办法在 UpdateModel(myViewModel, form.ToValueProvider());UpdateModel(myViewModel, form.ToValueProvider()); 期间绑定复选框列表(在视图中使用或不使用帮助器创建)甚至数据数组code> 阶段将填充模型内部的 IListstring[]

I am looking here to find a quick and easy way to bind a list of checkbox list items when the postback occurs in the model.

Apparently the common way to do it now seems to do it like this form.GetValues("checkboxList")[0].Contains("true"); It seems painfull and not exactly safe.

Is there a way to bind a list of checkbox (that are created with or without an helper in the view) or even an array of data for that matters during the UpdateModel(myViewModel, form.ToValueProvider()); phase which would populate an IList<string> or string[] inside of the model ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

简单 2024-10-22 14:52:20

您可以从模型开始:

public class MyViewModel
{
    public int Id { get; set; }
    public bool IsChecked { get; set; }
}

然后是控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new[] 
        {
            new MyViewModel { Id = 1, IsChecked = false },
            new MyViewModel { Id = 2, IsChecked = true },
            new MyViewModel { Id = 3, IsChecked = false },
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<MyViewModel> model)
    {
        // TODO: Handle the user selection here
        ...
    }
}

视图(~/Views/Home/Index.aspx):

<% using (Html.BeginForm()) { %>
    <%=Html.EditorForModel() %>
    <input type="submit" value="OK" />
<% } %>

最后是相应的编辑器模板:

<%@ Control 
    Language="C#"
    Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.MyViewModel>" %>
<%= Html.HiddenFor(x => x.Id) %>
<%= Html.CheckBoxFor(x => x.IsChecked) %>

现在,当您在 POST 操作中提交表单时,您可以将获取所选值的列表及其 id。

You could start with a model:

public class MyViewModel
{
    public int Id { get; set; }
    public bool IsChecked { get; set; }
}

then a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new[] 
        {
            new MyViewModel { Id = 1, IsChecked = false },
            new MyViewModel { Id = 2, IsChecked = true },
            new MyViewModel { Id = 3, IsChecked = false },
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<MyViewModel> model)
    {
        // TODO: Handle the user selection here
        ...
    }
}

a View (~/Views/Home/Index.aspx):

<% using (Html.BeginForm()) { %>
    <%=Html.EditorForModel() %>
    <input type="submit" value="OK" />
<% } %>

And finally a corresponding editor template:

<%@ Control 
    Language="C#"
    Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.MyViewModel>" %>
<%= Html.HiddenFor(x => x.Id) %>
<%= Html.CheckBoxFor(x => x.IsChecked) %>

Now when you submit the form in the POST action you will get the list of selected values along with their id.

何时共饮酒 2024-10-22 14:52:20

这是快速简便的方法。只需在 checkbox 输入元素中设置 value 属性,并为它们指定相同的name如果我在网站中实现此功能,我将创建一个 CheckBox 辅助方法,该方法采用 namevalueisChecked 参数,但这里是只包含所需 html 的视图:

<% using (Html.BeginForm()) { %>
  <p><input type="checkbox" name="checkboxList" value="Value A" /> Value A</p>
  <p><input type="checkbox" name="checkboxList" value="Value B" /> Value B</p>
  <p><input type="checkbox" name="checkboxList" value="Value C" /> Value C</p>
  <p><input type="checkbox" name="checkboxList" value="Value D" /> Value D</p>
  <p><input type="checkbox" name="checkboxList" value="Value E" /> Value E</p>
  <p><input type="checkbox" name="checkboxList" value="Value F" /> Value F</p>
  <input type="submit" value="OK" />
<% } %>

在您的控制器中:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(IEnumerable<string> checkboxList)
{
    if (checkboxList != null)
    {
        ViewData["Message"] = "You selected " + checkboxList.Aggregate("", (a, b) => a + " " + b);
    }
    else
    {
        ViewData["Message"] = "You didn't select anything.";
    }

    return View();
}

IEnumerable 参数(您可以将其设为 IList< /code> 如果需要)将仅包含选中项目的值。如果没有选中任何框,它将为 null

Here's the quick and easy way. Just set the value attribute inside your checkbox input elements and give them all the same name. If I was implementing this in a site, I would create a CheckBox helper method that takes name, value and isChecked parameters, but here's the View with just the html needed:

<% using (Html.BeginForm()) { %>
  <p><input type="checkbox" name="checkboxList" value="Value A" /> Value A</p>
  <p><input type="checkbox" name="checkboxList" value="Value B" /> Value B</p>
  <p><input type="checkbox" name="checkboxList" value="Value C" /> Value C</p>
  <p><input type="checkbox" name="checkboxList" value="Value D" /> Value D</p>
  <p><input type="checkbox" name="checkboxList" value="Value E" /> Value E</p>
  <p><input type="checkbox" name="checkboxList" value="Value F" /> Value F</p>
  <input type="submit" value="OK" />
<% } %>

In your Controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(IEnumerable<string> checkboxList)
{
    if (checkboxList != null)
    {
        ViewData["Message"] = "You selected " + checkboxList.Aggregate("", (a, b) => a + " " + b);
    }
    else
    {
        ViewData["Message"] = "You didn't select anything.";
    }

    return View();
}

The IEnumerable<string> parameter (you could make it IList<string> if you want) will contain only the values of the checked items. It will be null if none of the boxes are checked.

如果没有你 2024-10-22 14:52:20

使用自定义模型绑定器和常规 HTML 效果非常好...

首先,使用 Razor 语法的 HTML 表单:(

@using (Html.BeginForm("Action", "Controller", FormMethod.Post)) {
    <ol>
        <li><input type="textbox" name="tBox" value="example of another form element" /></li>

        <li><input type="checkbox" name="cBox" value="1" /> One</li>
        <li><input type="checkbox" name="cBox" value="2" /> Two</li>
        <li><input type="checkbox" name="cBox" value="3" /> Three</li>
        <li><input type="checkbox" name="cBox" value="4" /> Four</li>
        <li><input type="checkbox" name="cBox" value="5" /> Five</li>

        <li><input type="submit" /></li>
    </ol>
}

FormMethod.Post 也可以是 .Get,但不是这样。这并不重要)

然后,在正确的 MVC 意义上,有一个代表您的表单提交的模型对象:

public class CheckboxListExampleModel {
    public string TextboxValue { get; set; }
    public List<int> CheckboxValues { get; set; }
}

和一个自定义模型绑定器类(我喜欢将其放在正在绑定的模型中,所以我将重复上面创建的模型以显示我将其添加到里面还允许绑定器使用私有属性设置器,这是一件好事):

public class CheckboxListExampleModel {
    public string TextboxValue { get; private set; }
    public List<int> CheckboxValues { get; private set; }

    public class Binder : DefaultModelBinder {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
            var model = new CheckboxListExampleModel();

            model.TextboxValue = bindingContext.GetValueAsString("tBox");

            string checkboxCsv = bindingContext.GetValueAsString("cBox");
            // checkboxCsv will be a comma-separated list of the 'value' attributes
            //   of all the checkboxes with name "cBox" which were checked
            model.CheckboxValues = checkboxCsv.SplitCsv<int>();

            return model;
        }
    }
}

.GetValueAsString() 是一个扩展方法,为了清楚起见,它是:

    public static string GetValueAsString(this ModelBindingContext context, string formValueName, bool treatWhitespaceAsNull = true) {
        var providerResult = context.ValueProvider.GetValue(formValueName);
        if (providerResult.IsNotNull() && !providerResult.AttemptedValue.IsNull()) {
            if (treatWhitespaceAsNull && providerResult.AttemptedValue.IsNullOrWhiteSpace()) {
                return null;
            } else {
                return providerResult.AttemptedValue.Trim();
            }
        }
        return null;
    }

.SplitCsv() 也是一个扩展方法,但它是一个足够常见的需求和足够混乱的代码,我将把它作为练习留给读者。

最后,您处理表单提交的操作:

[HttpPost]
public ActionResult Action([ModelBinder(typeof(CheckboxListExampleModel.Binder))] CheckboxListExampleModel model) {
    // stuff
}

This works pretty well using a custom model binder and regular HTML...

First, your HTML form in Razor syntax:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post)) {
    <ol>
        <li><input type="textbox" name="tBox" value="example of another form element" /></li>

        <li><input type="checkbox" name="cBox" value="1" /> One</li>
        <li><input type="checkbox" name="cBox" value="2" /> Two</li>
        <li><input type="checkbox" name="cBox" value="3" /> Three</li>
        <li><input type="checkbox" name="cBox" value="4" /> Four</li>
        <li><input type="checkbox" name="cBox" value="5" /> Five</li>

        <li><input type="submit" /></li>
    </ol>
}

(FormMethod.Post could also be .Get, doesn't matter for this)

Then, in proper MVC sense have a model object which represents your form submission:

public class CheckboxListExampleModel {
    public string TextboxValue { get; set; }
    public List<int> CheckboxValues { get; set; }
}

And a custom model binder class (I like to put this inside the model being bound, so I'll repeat the model created above to show where I'd add it. Placing it inside also allows the binder to use private property setters, which is a Good Thing):

public class CheckboxListExampleModel {
    public string TextboxValue { get; private set; }
    public List<int> CheckboxValues { get; private set; }

    public class Binder : DefaultModelBinder {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
            var model = new CheckboxListExampleModel();

            model.TextboxValue = bindingContext.GetValueAsString("tBox");

            string checkboxCsv = bindingContext.GetValueAsString("cBox");
            // checkboxCsv will be a comma-separated list of the 'value' attributes
            //   of all the checkboxes with name "cBox" which were checked
            model.CheckboxValues = checkboxCsv.SplitCsv<int>();

            return model;
        }
    }
}

.GetValueAsString() is an extension method used for clarity, here it is:

    public static string GetValueAsString(this ModelBindingContext context, string formValueName, bool treatWhitespaceAsNull = true) {
        var providerResult = context.ValueProvider.GetValue(formValueName);
        if (providerResult.IsNotNull() && !providerResult.AttemptedValue.IsNull()) {
            if (treatWhitespaceAsNull && providerResult.AttemptedValue.IsNullOrWhiteSpace()) {
                return null;
            } else {
                return providerResult.AttemptedValue.Trim();
            }
        }
        return null;
    }

.SplitCsv<T>() is also an extension method, but it's a common enough need and messy enough code that I'll leave it as an exercise for the reader.

And finally, your action to handle the form submit:

[HttpPost]
public ActionResult Action([ModelBinder(typeof(CheckboxListExampleModel.Binder))] CheckboxListExampleModel model) {
    // stuff
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文