Submit Form without Page Refresh in ASP.Net MVC

Here's an example of how you can use Ajax.BeginForm to submit a form without postback in ASP.NET MVC. We'll assume that you have a class called Person with three properties: Name, Email, and Age.
@model Person

@using (Ajax.BeginForm("SubmitForm", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "result" }, new { id = "myForm" }))
{
    
@Html.LabelFor(m => m.Name) @Html.TextBoxFor(m => m.Name)
@Html.LabelFor(m => m.Email) @Html.TextBoxFor(m => m.Email)
@Html.LabelFor(m => m.Age) @Html.TextBoxFor(m => m.Age)
}
Controller Code:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult SubmitForm(Person person)
    {
        // Code to save person data to database or perform other operations
        return Content("Form submitted successfully!");
    }
}
Explanation:
In the view, we're using Ajax.BeginForm to create a form that will be submitted using AJAX. We've specified the controller action that will handle the form submission ("SubmitForm" in this case) and set the HTTP method to POST. We've also specified an update target ID, which will be used to update the result of the form submission.

We've also added three textboxes for the Name, Email, and Age properties of the Person class.

In the controller, we have two actions. The Index action returns the view that contains the form. The SubmitForm action is decorated with the HttpPost attribute, indicating that it should only be called when the form is submitted using the POST method.

The SubmitForm action takes a Person object as a parameter, which will be populated with the data from the form when the form is submitted. In this example, we're just returning a string to indicate that the form was submitted successfully, but you could perform any other actions you need to here, such as saving the data to a database or sending an email.

Note: To use Ajax.BeginForm, you need to include the jQuery and unobtrusive-ajax scripts in your project. You can do this by adding the following lines to your layout file:


Replace {version} with the version of jQuery that you're using.
 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice