Use*_*863 6 javascript controller asp.net-mvc-3
如果我尝试从我的Controller返回一些JavaScript,如下所示:
public ActionResult DoSomething()
{
return JavaScript("alert('Hello world!');");
}
Run Code Online (Sandbox Code Playgroud)
我没有在我的浏览器中查看警报消息,但是我从名为action的页面获取了.js脚本的下载请求(在我的情况下是register.js).怎么了?
Car*_*cke 14
当将结果作为a返回时,我遇到了类似的问题,指定的JavaScript没有执行JavaScriptResult.就我而言,JavaScript内容在<pre>标记内呈现为文本.
解决方案是ContentResult使用该Content()方法将JavaScript作为a返回.所以尝试:
public ActionResult DoSomething()
{
return Content("<script language='javascript' type='text/javascript'>alert('Hello world!');</script>");
}
Run Code Online (Sandbox Code Playgroud)
我在ASP.NET论坛上找到了答案.在下面的链接中查看Bruce的答案,以更全面地解释为什么以这种方式完成:
我不会返回Javascript,我会返回Content,然后在页面上,我会将该内容转换为警报:
public ActionResult DoSomething()
{
return Content("Hello world!");
}
$.ajax({
url: "/Action/DoSomething/",
type: "POST",
success: editSuccess,
error: editFailure
});
function editSuccess(data) {
alert(data);
}
Run Code Online (Sandbox Code Playgroud)
尝试下面的方法。
public ActionResult DoSomething(){
return Json(new {isok=true, message="Your Message", data=...});
//True / False Json Return
//return UserObj == null ?
//Json(true, JsonRequestBehavior.AllowGet) :
//Json(string.Format("YourObject '{0}' to String", YourObject),
//JsonRequestBehavior.AllowGet);
}
//view
$.ajax
{
//code
success :function(returnvalue)
{
if(!returnvalue.isok)
{
window.alert("Error:" + returnvalue.message);
}
else
{
//do the stuff with returnvalue.data
}
}
Run Code Online (Sandbox Code Playgroud)