我有一个 JavaScript 变量,它应该保存单击按钮时生成的 Razor 代码:
$("#addNewCatBtn").click(function(e){
e.preventDefault();
counter++;
var html = '<label class="col-md-2 control-label">İçerik Kategorisi</label><div class="col-md-3">'+
'@{ List<SelectListItem> modCatList = new List<SelectListItem>(); if (Model.CategoryList != null && Model.CategoryList.Count > 0) { foreach (var cat in Model.CategoryList) { modCatList.Add(new SelectListItem { Text = cat.CategoryName, Value = cat.ModCategoryId.ToString(), Selected = false }); } } else { modCatList.Add(new SelectListItem { Text = "Kategori Yok", Value = "0", Selected = true }); } } @Html.DropDownList("ModCategoryId_"+Html.Raw("counter"), modCatList, new { @class = "select2-select-00 col-md-12 full-width-fix required", @data_rule_required = "true", @data_msg_required = ModerationWEB.ErrorMessages.NOTVALID_MODCAT_EMPTY }) </div> '
+'<label class="col-md-2 control-label">Süreç Kategorisi</label> <div class="col-md-3"> '+
'@{ List<SelectListItem> flowCatList = new List<SelectListItem>(); if (Model.FlowCatList != null && Model.FlowCatList.Count > 0) { foreach (var cat in Model.FlowCatList) { flowCatList.Add(new SelectListItem { Text = cat.CategoryName, Value = cat.FlowCategoryId.ToString(), Selected = false }); } } else { flowCatList.Add(new SelectListItem { Text = "Kategori Yok", Value = "0", Selected = true }); } } @Html.DropDownList("FlowCatId_" +Html.Raw("counter"), flowCatList, new { @class = "select2-select-00 col-md-12 full-width-fix required", @data_rule_required = "true", @data_msg_required = ModerationWEB.ErrorMessages.NOTVALID_MODCAT_EMPTY, @multiple = "multiple", @size = "5" }) </div>';
$("#modFlowCatGroupDiv").html();
});
当它生成列表元素时,选项会换行,并导致 JavaScript 给出未终止的字符串常量
错误。我怎样才能阻止这个?
最佳答案
在您的代码中,modCatList
和 flowCatList
应该在 JS 之外构造。
如果我没记错的话,Html.DropDownList
返回一个 MvcHtmlString
,这样你就可以在 JS 中添加以下内容:
var html = '<label class="col-md-2 control-label">İçerik Kategorisi</label><div class="col-md-3">'+
'@Html.DropDownList("ModCategoryId_"+Html.Raw("counter"), modCatList, new { @class = "select2-select-00 col-md-12 full-width-fix required", @data_rule_required = "true", @data_msg_required = ModerationWEB.ErrorMessages.NOTVALID_MODCAT_EMPTY }).ToHtmlString().Replace(Environment.NewLine, "") </div> '
+'<label class="col-md-2 control-label">Süreç Kategorisi</label> <div class="col-md-3"> '+
'@Html.DropDownList("FlowCatId_" +Html.Raw("counter"), flowCatList, new { @class = "select2-select-00 col-md-12 full-width-fix required", @data_rule_required = "true", @data_msg_required = ModerationWEB.ErrorMessages.NOTVALID_MODCAT_EMPTY, @multiple = "multiple", @size = "5" }).ToHtmlString().Replace(Environment.NewLine, "") </div>';
您可能需要对渲染的代码进行转义,
$("#modFlowCatGroupDiv").html(unescape(html));
关于javascript - Razor 代码在 JavaScript 字符串内创建新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28605198/