asp.net-mvc-5asp.net-ajaxajax.beginformunobtrusive-ajax

Ajax.BeginForm change AjaxOptions depending on submit value


How can I change the values ​​of the AjaxOptions depending on the submit value of the pressed button.

In View:

@using (Ajax.BeginForm("function_name", "Controller",
new AjaxOptions
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "resultsLoad",
    OnBegin = "function_onBegin",
    OnFailure = "function_onFailure",
    OnSuccess = "function_onSuccess",
    OnComplete = "function_onComplete"
})) {
<button type="submit" id="btn_1" value="submit1" name="submit"></button>
<button type="submit" id="btn_2" value="submit2" name="submit"></button>
}

In Controller:

[HttpPost]
public ActionResult function_name(IndexViewModel model, string submit)
{ 
    enter code...
    return PartialView();
}

When I post by pressing any of the buttons, I need to change the AjaxOptions values ​​before returning the new PartialView.


Solution

  • The ajax on begin function contains a second parameter (not documented) "request", that is an object with the form request info.

    function function_onBegin(xhr, request) {
        //console.log(request);
        //request.data = submited form data as json string
        var requestData = request.data;    
    
        if (requestData.indexOf('anyCondition') >= 0) {
            //do something        
        } else {
            // do something else
        }
    }
    

    Access into request data allows to implement some conditional to accomplish required behaviour.