Call javascript from MVC controller action

后端 未结 9 1439
半阙折子戏
半阙折子戏 2021-02-01 07:04

Can I call javascript function from MVC controller action (not from view page) and get return value? How?


I need to make request to server

9条回答
  •  轮回少年
    2021-02-01 07:23

    For those that just used a standard form submit (non-AJAX), there's another way to fire some Javascript/JQuery code upon completion of your action.

    First, create a string property on your Model.

    public class MyModel 
    {
        public string JavascriptToRun { get; set;}
    }
    

    Now, bind to your new model property in the Javascript of your view:

    
    

    Now, also in your view, create a Javascript function that does whatever you need to do:

    
    

    Finally, in your controller action, you need to call this new Javascript function:

    [HttpPost]
    public ActionResult PurchaseCart(MyModel model)
    {
        // Do something useful
        ...
    
        if (success == false)
        {
            model.JavascriptToRun= "ShowErrorPopup()";
            return View(model);
        }
        else
            return RedirectToAction("Success");
    }
    

提交回复
热议问题