问题描述
我需要使用jQuery动态添加一些元素.因此,我在互联网上进行了查找,发现此.当单引号中包含纯HTML元素时,它很好并且可以正常工作.我需要在jQuery中使用剃刀语法.
I need to use jQuery to add some elements dynamically. So I looked up in the internet and I found this. It is nice and working when there is plain html elements inside single quotes. I need to use razor syntax with jQuery.
我知道jQuery是用户端,而razor是服务器端.它们不能组合在一起.我在这里问是因为我需要知道如何实现这一目标.
I understand that jQuery is user side and razor is server side. They cannot be combined together. I am asking here because I need to know how do i achieve this.
我无法使用的jQuery如下:
My not working jQuery is as follows:
<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))
};
});
我的目标类似于教程-动态添加元素.在这里,我在单击按钮时添加了标签和下拉菜单.我该如何实现?
My aim is similar to the tutorial - to add elements dynamically. Here I am adding a label and dropdown on the click of button. How do I achieve this?
推荐答案
您不能使用JQuery添加Razor元素,因为正如您已经说过的那样,JQuery是客户端库,而使用Razor语法的ASP.NET是服务器端脚本语言.
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.
如果要添加使用Razor语法创建的元素,则将隐藏元素添加到页面并使用JQuery添加将其克隆到DOM.
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());
这篇关于如何在ASP.NET MVC 5中使用带有razor语法的jquery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!