簡體   English   中英

如何在剃須刀內逃脫字符串?

[英]How to escape string within razor?

我有一個使用foreach填充的列表框。 (有關為什么需要這樣做的詳細說明。)我需要對字符串進行轉義,因為fname和lname可以包含特殊字符,例如'或“。

foreach (var cust in item.Customers)
{
    var custString = string.Format("{0}%#%{1}%#%{2}", cust.CustID, cust.LName, cust.FName);

    <option value="@custString">@cust.DisplayName</option>
}

設置值后,有什么方法可以對custString進行JavaScript轉義嗎? 還是有一種首選的C#轉義方式,將與javascript的unescape一起很好地工作,我正在使用unescape轉換這些字符。

那就是AttributeEncode助手的作用:

<option value="@Html.AttributeEncode(custString)">@cust.DisplayName</option>

但是,嘿,你在做什么? foreach循環生成一個下拉列表????

嘗試使用Html.DropDownListFor幫助程序,並在視圖為時過晚之前停止視圖中的出血。 該幫助程序會按照其名稱所示執行操作。 並負責編碼和轉義等。

因此,只需定義一個視圖模型:

public class MyViewModel
{
    public string CustomerId { get; set; }
    public IEnumerable<SelectListItem> Customers { get; set; }
}

然后繼續執行您的控制器操作,然后將此視圖模型傳遞給視圖:

public ActionResult Index()
{
    IEnumerable<Customer> customers = ... fetch the domain model from your DAL or something
    // map to a view model:
    var viewModel = new MyViewModel
    {
        Customers = customers.Select(x => new SelectListItem
        {
            Value = x.CustID,
            Text = string.Format("{0}%#%{1}%#%{2}", x.CustID, x.LName, x.FName)
        })
    };

    // pass the view model to the view:
    return View(viewModel);
}

在視圖內部,當您需要生成下拉列表時,請使用DropDownListFor助手:

@Html.DropDownListFor(x => x.CustomerId, Model.Customers)

暫無
暫無

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

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