12

大家早。

我可以看到这已在其他地方讨论过,但想知道对于像我这样的傻瓜来说,MVC 4 中是否有任何变化或事情变得更简单?!

设想

我有以下经过编辑的模型

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; }
}

使用以下标准创建视图

 <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>

这给了我一个开箱即用的漂亮下拉列表,来自Scott Gu 的博客

现在我真正的问题是 - 我如何有效地将这个下拉框转换为有效的多选复选框列表?

再次道歉,我只是在试水,看看是否发生了任何更新。

请注意,第一个 MVC 项目,所以慢慢来,我又觉得很厚:'(

4

4 回答 4

19

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.

于 2012-06-27T10:03:45.127 回答
5

不错的解决方案 -

仅供其他人参考 - 我和你一样,需要一个复选框列表 - 我一直在这里使用它:

http://www.codeproject.com/Articles/292050/CheckBoxList-For-a-missing-MVC-extension

它工作得很好......写得很好 - 希望这可以帮助某人。

罗兰

于 2012-09-28T20:02:43.890 回答
2

ASP.NET MVC 4 RC 在这方面没有发生任何变化,并且在它达到 RTM 时不太可能发生。

但是你仍然可以实现一个自定义助手来实现这一点。你甚至可以改进这个帮助器,让它将 lambda 表达式作为第一个参数而不是字符串,以便获得强类型版本。

如果您不使用枚举,这里是另一个示例

于 2012-06-26T09:38:15.817 回答
1

如果将选定的值传递给 MultiSelected(参数 #4)

ViewBag.VfonctionIds = new MultiSelectList(db.tbIntervenantFonctionTypes, "intervenantFonctionType_id", "Nom", fonctionSelected);  

将助手更改为

        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;

        //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,
                                                (item.Selected) ? "checked=\"checked\"" : "",                                                    
                                                item.Text);
        }

        return MvcHtmlString.Create(divTag.ToString());
    }
于 2014-07-07T21:16:25.797 回答