簡體   English   中英

如何使Html.DropDownList對其值進行編碼?

[英]How can I make Html.DropDownList encode its values?

在我的viewData中,我有一個IList mls。 我想用它來顯示一個下拉菜單。 像這樣:

<%= Html.DropDownList("ml3Code", 
        new SelectList(Model.Mls, "Code", "Description", Model.Ml3.Code ?? ""),
            Model.T9n.TranslateById("Labels.All"),
            new { @class = "searchInput" })%>

直到出現myObject.Code == VOC <420 g / l為止,這都可以正常工作。 我本來希望HTML幫助程序可以對它的值進行編碼,但事實並非如此。 我應該如何解決這個問題? 我唯一能想到的是,首先用編碼值制作對象的重復列表,然后將其饋送到選擇列表。 這真的很麻煩。

PS我希望Phill H.和他的團隊對asp.net-mvc 2.0的編碼有一個長而透徹的了解...

我很困惑 之前在SO上問過“ 是否像Html.DropDownList()這樣的ASP.NET MVC輔助方法對輸出的HTML進行編碼? ”這個問題,答案是“是”-引用了MVC框架的源代碼來對此進行支持。斷言。

好吧,您可以使用自己的HTML幫助器,但是如果您像我一樣,就不想這樣做。

對我來說,我在這里看到兩個選擇:

  1. 在沒有幫助者的情況下以純視圖形式編寫選擇元素。 我從來沒有覺得助手會為您在出現錯誤時突出顯示元素提供很大的節省。

  2. 頁面加載時,在客戶端上修補選擇框,如下所示:

函數encodeHtml(str){var encodeHtml = escape(str); encodeHtml = encodeHtml.replace(/// g,“%2F”); encodeHtml = encodeHtml.replace(/ \\?/ g,“%3F”); encodeHtml = encodeHtml.replace(/ = / g,“%3D”); encodeHtml = encodeHtml.replace(/&/ g,“%26”); encodeHtml = encodeHtml.replace(/ @ / g,“%40”); 返回encodingHtml; }

window.onload = function()
{
  var ml3Code = document.getElementById("ml3Code");

  for(var i = 0; i < ml3Code.options.length; ++i)
  {
  ml3Code.options[i].value = encodeHtml(ml3Code.options[i].value);
  }
};

我知道這是駭客。 我非常喜歡首選。

這是編碼的。 但是不要與螢火蟲一起檢查-它會顯示已解碼的值。

在瀏覽器的ViewSource中簽入,並進行編碼。

控制者

    public List<CategoryInfo> GetCategoryList()
    {
        List<CategoryInfo> categories = new List<CategoryInfo>();
        categories.Add(new CategoryInfo { Name = "Food<äü", Key = "VOC<420 g/l", ID = 2, Uid = new Guid("C0FD4706-4D06-4A0F-BC69-1FD0FA743B07") });

    }


    public ActionResult Category(ProductViewModel model )
    {

        IEnumerable<SelectListItem> categoryList  =
                                   from category in GetCategoryList()
                                   select new SelectListItem
                                   {
                                       Text = category.Name,
                                       Value = category.Key
                                   };
        model.CategoryList = categoryList;



      return View(model);
    }

視圖

  <%= Html.DropDownList("Category" , Model.CategoryList) %>

模型

public class ProductViewModel
{
    public IEnumerable<SelectListItem> CategoryList { get; set; }
    public List<CategoryInfo> Categories { get; set; }


}

的HTML

      <select id="Category" name="Category"><option value="VOC&lt;420 g/l">Food&lt;&#228;&#252;</option>
</select>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM