Can i return javascript from MVC controller to View via Ajax request

落花浮王杯 提交于 2019-11-29 11:40:28

Is it possible to return java script in the form of string from controller actions

You could return a JavaScriptResult:

[HttpPost]
public ActionResult TestAjax(FormCollection form)
{
    int strnum1 = Convert.ToInt32(form["txtbox1"].ToString());
    int strnum2 = Convert.ToInt32(form["txtbox2"].ToString());
    return JavaScript("<script>alert(\"some message\")</script>");
}

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:

$.ajax({
    url: '/someaction',
    type: 'POST',
    data: { txtbox1: '12', txtbox2: '13' },
    dataType: 'script'
});

As an alternative you could return a JsonResult which will serialize the model to a JSON string:

[HttpPost]
public ActionResult TestAjax(FormCollection form)
{
    int strnum1 = Convert.ToInt32(form["txtbox1"].ToString());
    int strnum2 = Convert.ToInt32(form["txtbox2"].ToString());
    string strnum3 = Convert.ToString(strnum1 + strnum2);
    return Json(new { sum = strnum3 });
}

and then:

$.ajax({
    url: '/someaction',
    type: 'POST',
    data: { txtbox1: '12', txtbox2: '13' },
    success: function(result) {
        alert(result.sum);
    }
});

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:

public class SumViewModel
{
    public int TxtBox1 { get; set; }
    public int TxtBox2 { get; set; }
}

and then:

[HttpPost]
public ActionResult TestAjax(SumViewModel model)
{
    int sum = model.TxtBox1 + model.TxtBox2;
    return Json(new { sum = sum });
}

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?

[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 strnum3;
    }

    return string.Empty;

}

$.ajax({
    url: "/Controller/TestAjax/",
    type: "POST",
    data: /* form data here */,
    success: SuccessCallback,
    error: FailureCallback
});

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

Try this,

[HttpPost]
    public ActionResult 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 JavaScript("JSFunction(paramtr);");    
    }

View:-

function JSFunction(paramtr)
{

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!