2015-04-02 441 views
0

我從互聯網獲得了以下代碼,用於CheckboxListFor html助手擴展。目前,在SelectedValues中,它將從複選框列表中返回選定值的List<string>。我想在SelectedValues中得到一個逗號分隔的字符串。從CheckboxList獲取逗號分隔的字符串HTML助手

任何人都可以告訴我如何實現它嗎?

下面是代碼:

的HtmlHelper擴展:

 /// <summary> 
    /// Returns a checkbox for each of the provided <paramref name="items"/>. 
    /// </summary> 
    public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string listName, IEnumerable<SelectListItem> items, object htmlAttributes = null) 
    { 
     var container = new TagBuilder("div"); 
     foreach (var item in items) 
     { 
      var label = new TagBuilder("label"); 
      label.MergeAttributes(new RouteValueDictionary(htmlAttributes), true); 

      var cb = new TagBuilder("input"); 
      cb.MergeAttribute("type", "checkbox"); 
      cb.MergeAttribute("name", listName); 
      cb.MergeAttribute("value", item.Value ?? item.Text); 
      if (item.Selected) 
       cb.MergeAttribute("checked", "checked"); 

      label.InnerHtml = cb.ToString(TagRenderMode.SelfClosing) + item.Text; 

      container.InnerHtml += label.ToString(); 
     } 

     return new MvcHtmlString(container.ToString()); 
    } 

    private static IEnumerable<SelectListItem> GetCheckboxListWithDefaultValues(object defaultValues, IEnumerable<SelectListItem> selectList) 
    { 
     var defaultValuesList = defaultValues as IEnumerable; 

     if (defaultValuesList == null) 
      return selectList; 

     IEnumerable<string> values = from object value in defaultValuesList 
            select Convert.ToString(value, CultureInfo.CurrentCulture); 

     var selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase); 
     var newSelectList = new List<SelectListItem>(); 

     selectList.ForEach(item => 
     { 
      item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text); 
      newSelectList.Add(item); 
     }); 

     return newSelectList; 
    } 

    /// <summary> 
    /// Returns a checkbox for each of the provided <paramref name="items"/>. 
    /// </summary> 
    public static MvcHtmlString CheckBoxListFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, 
     Expression<Func<TModel, TValue>> expression, 
     IEnumerable<SelectListItem> items, object htmlAttributes = null) 
    { 
     var listName = ExpressionHelper.GetExpressionText(expression); 
     var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); 

     items = GetCheckboxListWithDefaultValues(metaData.Model, items); 
     return htmlHelper.CheckBoxList(listName, items, htmlAttributes); 
    } 

在視圖:

@Html.CheckBoxListFor(model => model.SelectedValues, Model.MySelectList) 

型號:

public class MyViewModel 
{   
     public SelectList MySelectList{ get; set; } 

     public List<string> SelectedValues{ get; set; } 

     //public string SelectedValues{ get; set; } Can I get comma separated string here 
} 

請注意,我需要逗號小號在控制器操作返回列表之後,從幫助程序返回的字符串沒有被分離出來。

爲什麼我試圖做到這一點?:

//Here in my model, I am getting `SelectedValues` which is a List<String>. 
public ActionResult Index(MyViewModel model) 
{ 
     //My code.... 
} 

在查看

//But I cannot save this list into RouteValueDictionary like: 
var searchCriteria = new RouteValueDictionary(); 
searchCriteria["model.SelectedValues"] = Model.SelectedValues; // List<string> cannot be save here. That's why I needed comma separated string. 
var viewDataDictionary = new ViewDataDictionary(); 
viewDataDictionary["searchCriteria"] = searchCriteria; 

@Html.Partial("_MyPagingView", Model.MyList, viewDataDictionary) 

有哪些要求Index的動作,當下一頁是_MyPagingView內部的整個機制點擊。爲了保持搜索狀態,我們需要將搜索到的數據保存在RouteValueDictionary之內。

+0

[的string.join(https://msdn.microsoft.com/en-us/library/57a79xd0%28v=vs.110%29。 ASPX)? – 2015-04-02 05:33:17

+0

把string.join放在哪裏?請注意,我需要從助手返回的逗號分隔的字符串,而不是在我回到列表之後。 – 2015-04-02 05:35:15

+0

您的助手正在生成一系列具有相同名稱的複選框。它只能回發和數組或值。您需要在服務器上生成以逗號分隔的字符串,或者在發佈之前使用javascript構建字符串並更新隱藏的輸入。 – 2015-04-02 05:38:40

回答

1

您可以創建一個輔助方法的SelectedValues添加到RouteValueDictionary

public void AddRoutes(List<string> values, string propertyName, RouteValueDictionary dictionary) 
{ 
    for (int i = 0; i < values.Count; i++) 
    { 
     string key = string.Format("{0}[{1}]", propertyName, i); 
     dictionary[key] = values[i]; 
    } 
} 

,然後用它作爲

var searchCriteria = new RouteValueDictionary(); 
AddRoutes(Model.SelectedValues, "SelectedValues", searchCriteria); 

,避免需要創建一個隱藏的輸入,並使用JavaScript

0

我更喜歡更改您的視圖模型的代碼:

public class MyViewModel 
{ 
    public SelectList MySelectList{ get; set; } 

    public List<string> SelectedValues { get; set; } 

    public string SelectedString 
    { 
     get 
     { 
      if (SelectedValues == null) return ""; 
      return string.Join(",", SelectedValues); 
     } 
     set 
     { 
      if (!string.IsNullOrEmpty(value)) 
      { 
       SelectedValues = value.Split(',').ToList(); 
      } 
     } 
    } 
} 

你可以得到逗號分隔字符串:

//In controller 
var selected = model.SelectedString; 

//In view 
searchCriteria["model.SelectedValues"] = Model.SelectedString;