【问题标题】:Render code into MVC view using jQuery使用 jQuery 将代码渲染到 MVC 视图中
【发布时间】:2012-05-05 03:06:42
【问题描述】:

我有一个字符串以字符串的形式到达我的控制器。它是一个具有以下元素模板的 List(Model.ToParticipantList):

string.Format("<li id=\"Id_{0}" style=\"font-weight: bold; margin-top: 1px; list-style-type: none; display: inline; margin-bottom: 3px; cursor: pointer; font-size: 11px; color: Black; padding-top: 1px; padding-bottom: 1px; margin-left: 2px; width: 150px;\" 
onclick=\"RemFromList('{0}__#{2}');\">
<a>{1}</a>
</li>,", el.Id, el.Name, "To"));

我希望将其传递给我的 jQuery 函数并产生以下结果:

<li id="Id_1" style="font-weight: bold; margin-top: 1px; list-style-type: none; display: inline; margin-bottom: 3px; cursor: pointer; font-size: 11px; color: Black; padding-top: 1px; padding-bottom: 1px; margin-left: 2px; width: 150px;" onclick="RemFromList('1__#To');">
<a>System System</a>
</li> 

这行得通:

             document.getElementById('To1').innerHTML=@Html.Raw(Model.ToParticipantList);  //this works 
          // $("#To1").html('@Html.Raw(Model.ToParticipantList)');  //this doesn't 
          // $("#To1").append('@Html.Raw(Model.ToParticipantList)'); //this doesn't 

在最后两个示例中我做错了什么?

【问题讨论】:

  • 页面其余部分的 HTML 是什么样的?具体来说,id 为“To1”的元素是如何定义的?
  • To1 是一个 div,其中包含以水平 li 显示的 li 元素。 RemFromList 函数从列表中删除元素。

标签: jquery asp.net-mvc asp.net-mvc-3 model-view-controller


【解决方案1】:

任何插入 HTML 的方法都应该有效。如果你举这个简单的例子:

<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<script type="text/javascript">
   document.getElementById( 'div1' ).innerHTML = '@Html.Raw("<li>Using getElementById</li>")';
   $( "#div2" ).html( '@Html.Raw("<li>Using jQuery html</li>")' );
   $( "#div3" ).append( '@Html.Raw("<li>Using jQuery append</li>")' );
</script>

它将在 DOM 中呈现此 HTML:

<div id="div1"><li>Using getElementById</li></div>
<div id="div2"><li>Using jQuery html</li></div>
<div id="div3"><li>Using jQuery append</li></div>

基本上它们都达到了相同的结果。代码中一定有一些您没有在示例中显示的内容。我确实在您的代码清单中注意到,当您使用 getElementById 时,Html.Raw 不像您为 jQuery html 所做的那样被单引号包围strong> 和 append 方法。如果您在 ToParticipantList 中包含的字符串中包含单引号,它将不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-06
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多