如何在ASP.NET MVC 5中使用带有razor语法的jquery?

Gau*_*han 5 javascript asp.net asp.net-mvc jquery razor

我需要使用jQuery动态添加一些元素。因此,我在互联网上查找后发现了这一点。当单引号内包含简单的html元素时,它很好并且可以工作。我需要在jQuery中使用剃刀语法。

我知道jQuery是用户端,而剃须刀是服务器端。它们不能组合在一起。我在这里问是因为我需要知道如何实现这一目标。

我无法使用的jQuery如下所示:

<script type="text/javascript">  
    $(document).ready(function () {  
        $(document).on("click", ".btnPlus", function () { 
        var html = '<div class="form-group">'+
                '@Html.LabelFor(model => model.transaction_item, "transaction_item", htmlAttributes: new { @class = "control-label col-md-2" })'+ 

                '<div class="col-md-4">'+
                    '@Html.DropDownList("transaction_item", null, htmlAttributes: new { @class = "form-control" })'+
                    '@Html.ValidationMessageFor(model => model.transaction_item, "", new { @class = "text-danger" })'+
                '</div>'+

                '<div class="col-md-6"><input type="button" class="BtnPlus" value="+" /></div>'+

            '</div>'
        $("#trItem").append($(html))
    };
});
Run Code Online (Sandbox Code Playgroud)

我的目标类似于本教程 -动态添加元素。在这里,我在单击按钮时添加了标签和下拉菜单。我该如何实现?

AGB*_*AGB 5

You cannot add Razor elements using JQuery because, as you have stated, JQuery is a client side library and ASP.NET using Razor syntax is a server side scripting language.

If you want to add elements created using Razor syntax then add a hidden element to the page and use JQuery to add a clone of it to the DOM.

Something like this should give you an idea of what I mean:

@Html.DropDownList("transaction_item", null, htmlAttributes: new { @class = "form-control", @id = 'template-ddl' })

$("#trItem").append($('#template-ddl').clone());
Run Code Online (Sandbox Code Playgroud)


dev*_*ric 5

You can create a partial page _MyPartial.cshtml in your Views Shared folder.

Then in your view reference add the reference to your scripts section

@section Scripts {
    @Html.Partial("~/Views/Shared/_MyPartial.cshtml",Model);
}
Run Code Online (Sandbox Code Playgroud)

部分页面: _MyPartial.cshtml

@model MyViewModel

<script type="text/javascript">  
$(document).ready(function () {  
    $(document).on("click", ".btnPlus", function () { 
    var html = '<div class="form-group">'+
            '@(Html.LabelFor(model => model.transaction_item, "transaction_item", htmlAttributes: new { @class = "control-label col-md-2" }))'+ 

            '<div class="col-md-4">'+
                '@(Html.DropDownList("transaction_item", null, htmlAttributes: new { @class = "form-control" }))'+
                '@(Html.ValidationMessageFor(model => model.transaction_item, "", new { @class = "text-danger" }))'+
            '</div>'+

            '<div class="col-md-6"><input type="button" class="BtnPlus" value="+" /></div>'+

        '</div>'
    $("#trItem").append($(html))
};
</script>
Run Code Online (Sandbox Code Playgroud)