繁体   English   中英

将Javascript变量插入到HTML.Partial ViewDataDictionary ASP.NET MVC中

[英]Insert Javascript variable into Html.Partial ViewDataDictionary ASP.NET MVC

我有一个javascript函数,当它被调用时,我想在div中插入一个partial。 一切工作正常,但是,当我要将一些javascript传递到Html.Partial ViewDataDictionary时,它没有传递呈现的javascript。

<script>

function addExperience() {

     @{var uid = @MvcHtmlString.Create("new Date().getTime()");}
     console.info(@uid); //output ok !

     var partialView = @(Html.Raw(JsonConvert.SerializeObject(Html.Partial("~/Views/Dashboard/_editUserExperience.cshtml", Model,  new ViewDataDictionary { { "id", uid } }).ToString().Trim('"'))))

     $("#newExperienceSection").append(partialView); //it renders "new Date().getTime(), not the number
}

</script>

谢谢 !

如果您使用字符串(Html.Partial返回一个字符串)调用Jsonconvert.SerializeObject,它将返回一个字符串。

因此,您声明var partialView = ...将呈现为

var partialView = "the contents of the partial view";

这就是为什么,当您这样做时:

$("#newExperienceSection").append(partialView);

它实际上将javascript显示为文本。

如果要获取执行JavaScript的局部视图,则可以在脚本标签内返回javascript,并将其添加到DOM中就可以执行它,例如,将_editUserExperience.cshtml设置为:

<script>
  alert('this gets executed as soon as you do add this to the DOM with the jQuery append command');
</script>

执行$("#newExperienceSection").append(partialView); 您会看到警报。

插入部分视图的一种更简单的方法是利用$ .ajax的优势,例如,在addExperience

$.get('@Url.Action("ActionMethodThatReturnsPartial", "YourController")').done(function(theHtmlReturned) { 
  $("#newExperienceSection").html(theHtmlReturned);
});

($ .get只是使用get请求的$ .ajax的简写)

资料来源: http//api.jquery.com/jquery.ajax/

http://api.jquery.com/jquery.get/

http://api.jquery.com/category/deferred-object/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM