【问题标题】:Passing Parameter Name to DropDownList Inside `` (back-tic or grave accent)将参数名称传递给 DropDownList 内部
【发布时间】:2019-08-01 03:31:31
【问题描述】:

在我的 cshtml 和我的脚本中,我有以下有效的循环:

              for (var i = 0; i < xValue.length; i++) {
                var obj = xValue[i];

                if (obj.NameOfViewData.slice(0, obj.NameOfViewData.indexOf("_")) == $("#SeriesTypeId option:selected").text().replace(" ", "")) {
                    console.log(obj.NameOfViewData);
                    console.log(obj.NameOfViewData.slice(0, obj.NameOfViewData.indexOf("_")));

                    var iname = "Pt_ReturnType";

                    $(container).append(`<div class="input" id=td` + iCnt + `_` + i + ` ` +
                        `value="Drops Element ` + iCnt + `_` + i + `">@Html.DropDownListFor(model => model.TagValueName, ViewData["Pt_ReturnType"] as SelectList, "--" + "testing" + "--")</div>`);

                }
            }

但是,当我尝试更改 ViewData 以接收具有相同名称的字符串 var 时,它不起作用。我尝试了什么(来自here 的想法):

$(container).append(`<div class="input" id=td` + iCnt + `_` + i + ` ` +
                                `value="Drops Element ` + iCnt + `_` + i + `">@Html.DropDownListFor(model => model.TagValueName, ViewData[`${iname}`] as SelectList, "--" + "testing" + "--")</div>`);

(这个“破坏”了 HTML 页面)

我也试过了:

$(container).append(`<div class="input" id=td` + iCnt + `_` + i + ` ` +
                            `value="Drops Element ` + iCnt + `_` + i + `">@Html.DropDownListFor(model => model.TagValueName, ViewData[iname] as SelectList, "--" + "testing" + "--")</div>`);

(这个,它不识别“iname as variable”)

请注意我使用的是 ` 而不是 "。原因是在我之前问过 here 的问题中。

【问题讨论】:

  • 不幸的是,这不是 Razor 语法的工作方式。 @Html 部分在服务器上进行评估,并且 ` 在那里无效。

标签: jquery razor dropdownlistfor


【解决方案1】:

我认为您需要在template literals 上阅读更多内容。

使用反引号时不需要连接。您可以使用占位符。

$(container).append(`<div class="input" id="td${iCnt}_${i}" value="Drops Element ${iCnt}_${i}">@Html.DropDownListFor(model => model.TagValueName, ViewData["Pt_ReturnType"] as SelectList, "--" + "testing" + "--")</div>`);

【讨论】:

  • 感谢您的回答,但是,我的问题是将参数传递给 ViewData 部分,而不是之前。对于“iCnts”和“i”,我能够传递数据。如果我尝试相同的方法 ViewData[${iname},它不会识别为我的 var。
  • 你不能。它需要在您的 razor 模板而不是 javascript 中定义,因为您的 razor 模板和 javascript 代码是两个独立的实体。
猜你喜欢
  • 2015-05-09
  • 2018-09-26
  • 2015-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多