ASP.NET MVC - Returning JavaScriptResult doesn'

2020-03-03 05:43发布

问题:

If I try to return some JavaScript from my Controller like this:

public ActionResult DoSomething()
{       
    return JavaScript("alert('Hello world!');");            
}

I do not view the alert message in my browser, but I get a download request for a .js script from the page named as the action (register.js in my case). What is wrong?

回答1:

Try the below.

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
}

}


回答2:

I had a similar problem with the specified JavaScript not executing when returning the result as a JavaScriptResult. In my case, the JavaScript content was rendering as text inside <pre> tags.

The solution is to return the JavaScript as a ContentResult, by using the Content() method. So try:

public ActionResult DoSomething()
{       
    return Content("<script language='javascript' type='text/javascript'>alert('Hello world!');</script>");            
}

I found the answer on the ASP.NET forums. Have a look at Bruce's answer at the following link for a more complete explanation of why it gets done this way:

Return JavascriptResult Not Working



回答3:

I would not return Javascript, I would return Content, then on the page, I would convert that content to an alert:

public ActionResult DoSomething()
{       
    return Content("Hello world!");            
}

$.ajax({
    url: "/Action/DoSomething/",
    type: "POST",
    success: editSuccess,
    error: editFailure
});

function editSuccess(data) {
   alert(data);
}


回答4:

If you need to return a js code using JavaScriptResult, keep in mind that your action should be called via ajax call. Calling this action via Html.Actionlink or other controls directly, results in showing your script text instead of running the script. So you need to add a js code in your view:

<script type="text/javascript">
    $(function () {
          $('#myButtonId').click(function () { 
                $.getScript("/MyController/DoSomething"); 
           });
    });
</script>

and your action in MyController:

public ActionResult DoSomething()
{       
    return JavaScript("alert('Hello world!');");            
}


回答5:

When you are calling your action from the view, make sure you use @Ajax.ActionLink instead of the @Html.ActionLink helper method. The JavaScript will then render correctly and your alert will display.