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

标签 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>

谢谢!

最佳答案

如果使用字符串调用 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/

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

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

关于javascript - 将 Javascript 变量插入 Html.Partial ViewDataDictionary ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28762010/

相关文章:

javascript - 相对布局,移动版显示不正确.. HTML/CSS

javascript - JavaScript 中的延迟函数

.net - Azure 上的 "You do not have permission to view this directory or page"Mvc 4 应用程序

asp.net - Quartz.net 和 Ninject : how to bind implementation to my job using NInject

asp.net-mvc - DataContractJsonSerializer ReadObject 异常

javascript - 窗口和屏幕尺寸发生变化

javascript - 制表符:是否可以为每行添加带有计算值的自定义列?

javascript - Angular 5 设置非 Angular 属性值

c# - FileStreamResult 不表示下载开始

asp.net - 来自 Microsoft.AspNet.WebApi.HelpPage 版本 4.0.30506 的运行时编译错误