在单引号内的 @Html.DropDownListFor 内返回 ViewBag

Returning ViewBag inside @Html.DropDownListFor inside single quotes

我有一个 DropDownListFor 以这种方式工作:

        <div class="form-horizontal" id=CurrencyDataBlock>
            @Html.DropDownListFor(model => model.Code, ViewBag.Currency as SelectList, "--Select Currency--", new { @class = "btn btn-default col-xs-12 col-xs-offset-0 col-sm-2" })
        </div>

我有一个 javascript 函数可以创建容器和字段。对于这个函数,我用这种方式在单引号之间传递整个容器:

    var part1 = '<br><br><hr style="height:1px;border:none;color:#333;background-color:#333;" /><div><input type="button" class="btn btn-default" onclick="ReTextBox(this)" value="Remove"/></div><textarea rows="10" cols="100" id="Text" name="dyntxt" style="width: 550px; height: 125px; margin-left: auto;"></textarea>'

但是,我的问题是当我尝试将 ViewBag(从第一个想法)传递给单引号时。我正在尝试这样:

var part3 ='<div class="form-horizontal" id=CurrencyDataBlock>@Html.DropDownListFor(model => model.Code, ViewBag.Currency as SelectList, "--Select Currency--", new { @class = "btn btn-default col-xs-12 col-xs-offset-0 col-sm-2" })</div>'

我也试过: @ViewBag.Currency

而且,还有: '@ViewBag.Currency'

没有任何效果。对于第一个选项,它给出了错误: "ReferenceError: DynamicText is not defined"。第二个想法给了我同样的错误。当我尝试放置单引号时,它甚至无法编译并给出错误: struct System.Char - 将字符表示为 UTF-16 代码单元。字符文字中的字符太多

最后,我尝试了这种方式: 我也试过这样(idea来自):

var part3 ='<div class="form-horizontal" id=CurrencyDataBlock>@Html.DropDownListFor(model => model.Code, ViewBag.Currency.Replace("\", "\\").Replace("'", "\'") as SelectList, "--Select Currency--", new { @class = "btn btn-default col-xs-12 col-xs-offset-0 col-sm-2" })</div>'

这种方式编译但页面确实加载。

有什么想法吗?

这是我认为你应该做的,

不使用单引号,而是使用 `。我真的不记得它叫什么了。这样你就可以在不考虑单引号或双引号问题的情况下编写 html

另外我不知道你的 HTML

中的 id=CurrencyDataBlock 是否是错字
var part3 = `<div class="form-horizontal" id="CurrencyDataBlock">
                @Html.DropDownListFor(model => model.headline, ViewBag.Currency as SelectList, "--Select Currency--", new { @class = "btn btn-default col-xs-12 col-xs-offset-0 col-sm-2" })
            </div>`;

var part1 = `<br><br>
                <hr style="height:1px;border:none;color:#333;background-color:#333;" />
                    <div><input type="button" class="btn btn-default" onclick="ReTextBox(this)" value="Remove"/></div>
                    <textarea rows="10" cols="100" id="Text" name="dyntxt" style="width: 550px; height: 125px; margin-left: auto;"></textarea>`;

此外,当您想要传递列表时,请考虑使用 @Html.Raw("your list or other variables here")