1

What is the difference if I return some JavaScript from my MVC controller as either

Content

[HttpPost]
    public ActionResult MyEndPoint([System.Web.Http.FromBody] string result)
    {
       string jsResponse = "<script>";

        if(result == "SUCCESS")
        {
            jsResponse = "SubmitOrder();";
        }
        else
        {
            jsResponse = "alert('Problem processing your order, please try again')";
        }
        jsResponse += "</script>";
        return Content(jsResponse);
    }

JavaScriptResult

  [HttpPost]
    public ActionResult MyEndPoint([System.Web.Http.FromBody] string result)
    {
       string jsResponse = "<script>";

        if(result == "SUCCESS")
        {
            jsResponse = "SubmitOrder();";
        }
        else
        {
            jsResponse = "alert('Problem processing your order, please try again')";
        }
        jsResponse += "</script>";
        return JavaScript(jsResponse);
    }

Also, are there any security precautions I need to be aware of when return JavaScript from a MVC controller method/call?

1 Answer 1

2

For one, a JavaScriptResult returns the response as application/javascript MIME type vs the default text/html that using Content() returns. Because of that, the JavaScriptResult won't do what it looks like you're attempting (executing the JS). The browser doesn't just execute anything sent to in in a response. Since Content() is actually sending HTML, the browser can render it, in this case executing the script in the script tag. I haven't seen JavaScriptResult used often, but where I have, it's usually used to serve scripts dynamically. For example:

Controller

public ActionResult SomeAction() {
    ...
    return JavaScript("script content");
}

View

<script src="MyController/SomeAction">

Regarding security, you'll obviously want to avoid executing anything that's been passed in from the user, whether that be from the request body, query string, etc. I'd wager, however it being a bit of a design issue and you couple your front end and back end, so regardless, it's probably best to use sparingly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.