Can I pass a parameter with the OnSuccess event in a Ajax.ActionLink

There is a better way to do this – use the built in parameters that the OnSuccess call can be expected to pass

the built in parameters (the ones I found so far anyway) are data, status and xhr

data = whatever you return from the action method

status = if successful this status is just a string that says “success”

xhr = object that points to a bunch of javascript stuff that I will not be discussing…

so you would define your javascript like this (you can leave out the arguments you don’t need – since all we want is our data back from the action we will just take the data argument)

function myOnSuccessFunction (data)
{
   ..do stuff here with the passed in data...
}

like I said before, data is whatever JSON that may be returned by the ActionResult so if your controller action method looks like this…

public ActionResult MyServerAction(Guid modelId)
{
   MyModel mod = new MyModel(modelId);

   mod.DoStuff();

   return Json(mod, JsonRequestBehavior.AllowGet);
}

you would set up your action link like this…

@Ajax.ActionLink("Do Stuff", "MyServerAction", new { modelId = Model.Id }, new     AjaxOptions { OnSuccess = "mySuccessScript(data);", OnFailure = "myFailureScript();", Confirm = "Are you sure you want to do stuff on the server?" })

this will create a confirmation message box asking if you want to actually invoke the action – clicking yes on the prompt will invoke the call to the controller – when the call comes back – the data argument will contain a JSON object of whatever you returned in your action method. Easy Peasy!

But wait! What if I want to pass another custom argument?! Simple! Just add your arguments to the front of the list…

instead of this…

function myOnSuccessFunction (data)
{
   ..do stuff here with the passed in data...
}

do this (you can have more than one custom argument if you like, just keep adding them as needed)…

function myOnSuccessFunction (myCustomArg, data)
{
   ..do stuff here with the passed in data and custom args...
}

then in your setup – just get the argument through some client side script within your ActionLink definition… i.e.

@Ajax.ActionLink("DoStuff", "MyServerAction", new { modelId = Model.Id }, new AjaxOptions { OnSuccess = "mySuccessScript(myClientSideArg, data);", OnFailure = "myFailureScript();", Confirm = "Are you sure you want to do stuff on the server?" })

Note that “myClientSideArg” in the OnSuccess parameter can come from wherever you need it to – just replace this text with what you need.

Hope That Helps!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)