Reputation: 5352
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?
Upvotes: 1
Views: 1030
Reputation: 6057
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.
Upvotes: 2