I am trying to do like this in ASP.net MVC 2.0 Application. I have a form with two fields number1 and number2.
I want add two these two numbers using an ajax request. In the controller, i am recieving two numbers ,adding them and storing result in another string. then, i am doing like this:
[HttpPost]
public string TestAjax(FormCollection form)
{
int strnum1 = Convert.ToInt32(form["txtbox1"].ToString());
int strnum2 = Convert.ToInt32(form["txtbox2"].ToString());
string strnum3 = Convert.ToString(strnum1 + strnum2);
if (strnum3 != null)
{
return "<script>alert("some message")</script>";
}
return string.Empty;
}
Is it possible to return java script in the form of string from controller actions
You could return a
JavaScriptResult
:For this to work you have to configure your AJAX request to execute javascript. For example if you are using jQuery that would look like this:
As an alternative you could return a JsonResult which will serialize the model to a JSON string:
and then:
As you can see here you are no longer mixing javascript with C# code in your controller. Respect the DRY principle. javascript belongs in javascript files.
As further improvement to this controller action I would recommend you introducing a view model and get rid of the terrible plumbing code of parsing stuff from the FormCollection. That's the responsibility of the default model binder.
So:
and then:
Conclusion: we have put this controller action on a diet, and moved the javascript where it belongs.
Why not use your ajax success callback function?
Try this,
View:-