How to call a Controller from View with Ajax

Nov 12, 2012 00:00 · 348 words · 2 minute read AJAX MVC Programming

Why you need an Ajax call ?

Some times you change small section of the big page and you don’t like your customer get a post back and see a blank page during the process .

How to do an Ajax call ?

There are several way to get around it , but one of the easiest way is to use “Ajax.BeginForm” function in a MVC project.

I am suppose you want to call the below controller method.

Code you have in your Controller

public string Action1(int id) {
		string result;
		//do something
		return result;
}

Put the below code in your view

Code that you need to put in ViewC#

@using (@Ajax.BeginForm("Action1", "Controller1", new AjaxOptions { UpdateTargetId = "#response", OnSuccess = "OnSuccess()", OnFailure = "OnFailure()", HttpMethod = "POST", OnBegin = "OnBegin()", OnComplete = "OnComplete()" }))
{
<input type="text" value="" name="id"/>
<input  type="submit"  />
}
  • Action1 is the name of your action in the controller class.
  • Controller1 is the name of your controller class.
  • UpdateTargetId is the name of element in your current view that will show the value of the “result” which come back from your Action1 method.
  • HttpMethod is the type of your form which can be “POST” or “GET” and depend on your Action1 method.
  • OnBegin , OnSuccess, OnComplete and OnFailure are the options that help you to call appropriate Javascript functions according to the result . for instance you can show an alert to the user if your call is successful by putting below code on your View file.

code that you should put in your viewJavaScript

<script type="text/javascript">
	function OnSuccess() {
		var successElement = document.getElementById("response");
		successElement.innerText = "Success";
	}
</script>

That’s all !

Have you still get a full post back rather than an ajax call ?

make sure that below settings are set in your web.config file .

settings that you should put in your web.config file

<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

and also you have reference the unobtrusive js file in your main Layout or bundle config .

file that you should put on your main layoutJavaScript

http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min.js