我有一个 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>
谢谢!
最佳答案
如果使用字符串调用 Jsonconvert.SerializeObject(Html.Partial 返回字符串),它会返回字符串。
所以你声明 varpartialView = ...将呈现为
var partialView = "the contents of the partial view";
这就是为什么,当你这样做时:
$("#newExperienceSection").append(partialView);
它实际上将 javascript 显示为文本。
如果您想获得部分 View 来执行 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);
时,您将看到警报。
插入部分 View 的更简单方法是利用 $.ajax,例如在 addExperience
中:
$.get('@Url.Action("ActionMethodThatReturnsPartial", "YourController")').done(function(theHtmlReturned) {
$("#newExperienceSection").html(theHtmlReturned);
});
($.get 只是使用 get 请求的 $.ajax 的简写)
来源:http://api.jquery.com/jquery.ajax/
关于javascript - 将 Javascript 变量插入 Html.Partial ViewDataDictionary ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28762010/