MVC 4,复选框列表和我 [英] MVC 4, Checkbox list and me

查看:137
本文介绍了MVC 4,复选框列表和我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上午全部。



我可以看到这已经在别处讨论过了,但是想知道如果有什么改变或事情在MVC 4中更简单,像我这样的单纯形? / p>

场景



我有以下编辑的 strong>:

  public class CorporateDetails 
{

public Guid? Id {get;组;

[Key]
public int CorporateDetailId {get;组; }

public int? EmsId {get;组; }
public string EmsName {get;组; }

public virtual EmsType EmsType {get;组;
}

public class EmsType
{
[Key]
public int? EmsId {get;组; }
public string EmsName {get;组; }

public virtual ICollection< EmsType> EmsTypes {get;组; }
}

使用以下标准创建视图

 < fieldset> 
< legend> CorporateDetails< / legend>



< div class =editor-label>
@ Html.LabelFor(model => model.EmsId,EmsType)
< / div>
< div class =editor-field>
@ Html.DropDownList(EmsId,String.Empty)
@ Html.ValidationMessageFor(model => model.EmsId)
< / div>
< div class =editor-label>
@ Html.LabelFor(model => model.EmsName)
< / div>
< div class =editor-field>
@ Html.EditorFor(model => model.EmsName)
@ Html.ValidationMessageFor(model => model.EmsName)
< / div>

< p>
< input type =submitvalue =Create/>
< / p>
< / fieldset>

这给我一个美丽的下拉列表a la Scott Gu的博客



现在我真正的问题是这样 - 如何有效地将这个下拉框转换成什么才能有效地多选择,复选框列表?



再次,道歉为了过渡,但我只是测试水,看是否有任何更新发生。



请注意,第一个MVC项目轻轻地走了,我又感觉很厚了:'(

解决方案

对了,我已经把它排序了 - hurray!从评论中可以看出,有一些问题出现,但请在下面找到完整的解决方案:D



模型

  public class CorporateDetails 
{

public Guid? Id {get;组;

[Key]
public int CorporateDetailId {get;组; }

public int [] EmsId {get;组;

}

public class EmsType
{
[Key]
public int EmsId {get;组; }
public string EmsName {get;组; }

public virtual ICollection< EmsType> EmsTypes {get;组;
}

控制器

  public ActionResult Create()
{
CorporateDetails corporatedetails = new CorporateDetails();
ViewBag.EmsId = new MultiSelectList(db.EmsTypes,EmsId,EmsName);
return View(corporatedetails);
}

扩展名(放在根目录中的文件夹中的项目)

  public static MvcHtmlString CheckBoxListFor< TModel,TProperty>(此HtmlHelper< TModel> htmlHelper,Expression&FunC& ,TProperty []>>表达式,MultiSelectList multiSelectList,对象htmlAttributes = null)
{
//导出复选框名称的属性名称
MemberExpression body = expression.Body as MemberExpression;
string propertyName = body.Member.Name;

//从ViewData模型获取当前选择的值
TProperty [] list = expression.Compile()。Invoke(htmlHelper.ViewData.Model);

//将选定的值列表转换为列表< string>为了方便操作
列表< string> selectedValues = new List< string>();

if(list!= null)
{
selectedValues = new List< TProperty>(list).ConvertAll< string>(delegate(TProperty i){return i.ToString ();});
}

//创建div
TagBuilder divTag = new TagBuilder(div);
divTag.MergeAttributes(new RouteValueDictionary(htmlAttributes),true);

//添加复选框
foreach(multiSelectList中的SelectListItem项)
{
divTag.InnerHtml + = String.Format(< div>< input type = \checkbox \name = \{0} \id = \{0} _ {1} \+
value = \{1} \\{2} />< label for = \{0} _ {1} \> {3}< / label>< / div>,
propertyName,
item.Value,
selectedValues.Contains(item.Value)?checked = \checked\:,
item.Text);
}

返回MvcHtmlString.Create(divTag.ToString());
}

在视图的网络配置中注册的扩展 / p>

 < pages pageBaseType =System.Web.Mvc.WebViewPage> 
< namespaces>
< add namespace =System.Web.Mvc/>
< add namespace =System.Web.Mvc.Ajax/>
< add namespace =System.Web.Mvc.Html/>
< add namespace =System.Web.Optimization/>
< add namespace =System.Web.Routing/>
< add namespace =MyProject.Extensions/>
< / namespaces>
< / pages>

查看

  @model Valpak.Websites.HealthChecker.Models.CorporateDetails 
@ {
ViewBag.Title =创建;
}
< h2>创建< / h2>
@using(Html.BeginForm())
{
@ Html.ValidationSummary(true)

< fieldset>
< legend> CorporateDetails< / legend>

< div class =editor-label>
@ Html.CheckBoxListFor(model => model.EmsId,(MultiSelectList)ViewBag.EmsId)
< / div>
< p>
< input type =submitvalue =Create/>
< / p>
< / fieldset>
}
< div>
@ Html.ActionLink(返回列表,索引)
< / div>
@section脚本{
@ Scripts.Render(〜/ bundles / jqueryval)
}

这给我一个可爱的复选框列表。 Hurray!



感谢Darin为您的帮助,我已经将此标记为答案,但是您的时间和精力都是+50。


Morning all.

I can see this has been discussed elsewhere but was wondering if anything had change or things made simpler in MVC 4 for simpletons like me?!

Scenario

I have the following,edited, model:

public class CorporateDetails
{

    public Guid? Id { get; set; }

    [Key]
    public int CorporateDetailId { get; set; }

    public int? EmsId { get; set; }
    public string EmsName { get; set; }

    public virtual EmsType EmsType { get; set; }
}

public class EmsType
{
    [Key]
    public int? EmsId { get; set; }
    public string EmsName { get; set; }

    public virtual ICollection<EmsType> EmsTypes { get; set; }
}

With the following standard create view:

 <fieldset>
    <legend>CorporateDetails</legend>



    <div class="editor-label">
        @Html.LabelFor(model => model.EmsId, "EmsType")
    </div>
    <div class="editor-field">
        @Html.DropDownList("EmsId", String.Empty)
        @Html.ValidationMessageFor(model => model.EmsId)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.EmsName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.EmsName)
        @Html.ValidationMessageFor(model => model.EmsName)
    </div>

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

This gives me, out of the box, a beautiful drop down list a la Scott Gu's blog

Now my real question is this - how can I effectively convert this drop down box to what will effectively be a multi select,checkbox list?

Again, apologies for going over trodden ground but I was just testing the water to see if any updates have occurred.

Please note, first MVC project so go gently, I'm feeling very thick again :'(

解决方案

Right ok, I have got it sorted - hurrah! As you can see from the comments, there were a few issues that came up but please find below the complete solution which DOES work :D

Model

 public class CorporateDetails
    {

        public Guid? Id { get; set; }

        [Key]
        public int CorporateDetailId { get; set; }

        public int[] EmsId { get; set; }

        }

    public class EmsType
    {
        [Key]
        public int EmsId { get; set; }
        public string EmsName { get; set; }

        public virtual ICollection<EmsType> EmsTypes { get; set; }
    }

Controller

 public ActionResult Create()
    {
        CorporateDetails corporatedetails = new CorporateDetails();
        ViewBag.EmsId = new MultiSelectList(db.EmsTypes, "EmsId", "EmsName");
        return View(corporatedetails);
    }

Extension (placed in a folder in the root of the project)

 public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty[]>> expression, MultiSelectList multiSelectList, object htmlAttributes = null)
    {
        //Derive property name for checkbox name
        MemberExpression body = expression.Body as MemberExpression;
        string propertyName = body.Member.Name;

        //Get currently select values from the ViewData model
        TProperty[] list = expression.Compile().Invoke(htmlHelper.ViewData.Model);

        //Convert selected value list to a List<string> for easy manipulation
        List<string> selectedValues = new List<string>();

        if (list != null)
        {
            selectedValues = new List<TProperty>(list).ConvertAll<string>(delegate(TProperty i) { return i.ToString(); });
        }

        //Create div
        TagBuilder divTag = new TagBuilder("div");
        divTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);

        //Add checkboxes
        foreach (SelectListItem item in multiSelectList)
        {
            divTag.InnerHtml += String.Format("<div><input type=\"checkbox\" name=\"{0}\" id=\"{0}_{1}\" " +
                                                "value=\"{1}\" {2} /><label for=\"{0}_{1}\">{3}</label></div>",
                                                propertyName,
                                                item.Value,
                                                selectedValues.Contains(item.Value) ? "checked=\"checked\"" : "",
                                                item.Text);
        }

        return MvcHtmlString.Create(divTag.ToString());
    }

Extension registered in web config of the Views

 <pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="MyProject.Extensions" />
  </namespaces>
</pages>

View

@model Valpak.Websites.HealthChecker.Models.CorporateDetails
@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>CorporateDetails</legend>

           <div class="editor-label">
           @Html.CheckBoxListFor(model => model.EmsId, (MultiSelectList) ViewBag.EmsId)
          </div>          
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Which gives me a lovely list of check boxes. Hurrah!

Thanks Darin for your help, I've marked this as the answer but +50 for your time and effort.

这篇关于MVC 4,复选框列表和我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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