将Javascript变量插入Html.Partial ViewDataDictionary ASP.NET MVC

时间:2015-02-27 09:48:58

标签: javascript asp.net-mvc

我有一个javascript函数,当它被调用时,我想在div中插入一个部分。一切正常,但是,当我想将一些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>

谢谢!

1 个答案:

答案 0 :(得分:2)

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

所以你说 var partialView = ...将呈现为

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

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

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

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

如果你想获得一个部分视图来执行javascript,你可以在脚本标签中返回javascript,并且只要你将它添加到DOM就会被执行,例如,如果你将_editUserExperience.cshtml设置为: / p>

<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/