In an MVC application, it is common to have a View that interacts with a Controller to perform various operations. One way to achieve this interaction is through the use of jQuery AJAX calls. In this blog post, we will discuss how to call a Controller method from a View using jQuery AJAX in .NET MVC and provide an example code snippet.
Firstly, let us discuss the Controller method we will be calling. Consider the following Controller code:
public class HomeController : Controller
{
public ActionResult MyMethod(string name)
{
ViewBag.Message = "Hello, " + name + "!";
return PartialView("_MyPartialView");
}
}
Here, we have a simple method named
MyMethod
that takes a string parameter
name
. This method simply returns a partial view
_MyPartialView
with a message that concatenates the provided
name
parameter.
Now, let us move on to the View that will call this method. Consider the following View code:
Here, we have a simple View with a textbox and a button. When the button is clicked, we use jQuery AJAX to call the
MyMethod
action method in the
HomeController
.
In the AJAX call, we specify the URL of the method using
@Url.Action("MyMethod", "Home")
. This will generate the correct URL for the method, taking into account the application's routing rules.
We then specify the HTTP method as POST, since the
MyMethod
method is decorated with the
[HttpPost]
attribute. We also provide the value of the
name
parameter using
$("#txtName").val()
, which gets the value of the textbox.
Finally, we specify the
success
callback function, which will be called when the AJAX call completes successfully. In this function, we simply set the HTML content of the
#result
div to the
result
parameter, which is the HTML returned by the
MyMethod
method.
In conclusion, calling a Controller method from a View using jQuery AJAX is a common scenario in MVC applications. By using the simple example code provided above, you can quickly implement this functionality in your own application.