MVC3 - 如何正确使用@ html.checkbox? [英] MVC3 - How to correctly use @html.checkbox?

查看:123
本文介绍了MVC3 - 如何正确使用@ html.checkbox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来MVC3,我无法弄清楚如何在MVC使用复选框。
我有我的看法一串文字像

I'm new to MVC3 and I can't figure out how to use checkboxes in MVC. I have a bunch of text in my view like

text1
text2
text3
text4
text5

submitbutton

这文字是不相关的任何模型它只是纯文本。我想向每个项目的复选框,并链接到控制器,这样当用户选择一些复选框的值并点击提交按钮我的控制器拿起哪些项目已经选定。
我试着使用@ html.checkbox(文字+指数),并尝试将控制器

This text is not related to any model its just plain text. I would like to place a checkbox for each item and a link it to the controller so that when a user selects some of the checkbox values and clicks on the submit button my controller picks up which items have been selected. I tried using @html.checkbox("text"+ index) and tried the controller to be

[HttpPost]
public ActionResult controller(List<string> list)
{
}

但是,这并不拿起选定项目清单。你能告诉我什么,我做错了,或另一种方式来做到这一点?

But that doesn't pick up the list of selected items. Can you tell me what i'm doing wrong or another way to do it?

推荐答案

与所有你的价值观创建一个视图模型。填充视图模型,并将其发送到视图。当事情被选中,你就会知道什么是什么的讯息。

Create a ViewModel with all of your values. Populate the ViewModel and send it to the view. When something is checked, you'll know what's what on the post.

public class MyModelViewModel
{
    public List<CheckBoxes> CheckBoxList {get; set;} 
    // etc
}

public class CheckBoxes
{
    public string Text {get; set;} 
    public bool Checked {get; set;}         
}

[HttpPost]
public ActionResult controller(MyModelViewModel model)
{
    foreach(var item in model.CheckBoxList)
    {
        if(item.Checked)
        {
            // do something with item.Text
        }
    }
}

基本上的ViewModels是你的朋友。你想为每个视图单独视图模型,这就是被来回传递的控制器和视图之间。然后,你可以做你的数据解析无论是在控制器或在服务层(pferably $ P $)。

Basically ViewModels are your friend. You want to have a separate ViewModel for each View, and it's what gets passed back and forth between the Controller and the View. You can then do your data parsing either in the controller, or (preferably) in a service layer.

序号:结果
应该在的ViewModels使用MVC每一个视图中使用?

这篇关于MVC3 - 如何正确使用@ html.checkbox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆