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:
<script type="text/javascript">
@Model.JavascriptToRun
</script>
Now, also in your view, create a Javascript function that does whatever you need to do:
<script type="text/javascript">
@Model.JavascriptToRun
function ShowErrorPopup() {
alert('Sorry, we could not process your order.');
}
</script>
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");
}
or
You can call a controller action from a JavaScript function but not vice-versa. How would the server know which client to target? The server simply responds to requests.An example of calling a controller action from JavaScript (using the jQuery JavaScript library) in the response sent to the client.$.ajax({ type: "POST", url: "/Controller/Action", // the URL of the controller action method data: null, // optional data success: function(result) { // do something with result }, error : function(req, status, error) { // do something with error } });orYes, it is definitely possible using Javascript Result:return JavaScript("Callback()");Javascript should be referenced by your view:function Callback(){ // do something where you can call an action method in controller to pass some data via AJAX() request }


0 comments:
Post a Comment
Note: only a member of this blog may post a comment.