In this article, we are going to discuss how we can post data to controller in asp.net core using Ajax with form serialize and without form serialize. With form serialize we also going to implement validation in form. We are not going to save or retrieve data from database we just post data to the controller. In this article, we are going to discuss following topics
- What is Ajax?
- How to use Ajax?
- Create Asp.Net Core Project
- Post Data without Form Serialize
- Add Validation in Form and Post Data with Form Serialize
What Is Ajax?
How to use Ajax?
Basic Properties of Ajax
- url: In this property you have to pass URL of your endpoint means when you want to post data.
- type: Specify the type of request POST, Get, Put, Delete etc.
- data: Data that you want to pass to a given endpoint.
- success: This property is a callback function called when request return with OK or 200 code means your request is successful. This callback function also returns response data that pass from controller side.
- error: This property is also a callback function that return when any error occurs while calling endpoint like endpoint not exist or bad request etc. This callback also have parameters which are request, status, and error.
- async: This is a Boolean property that is by default false. If you pass true in this property it will call this request asynchronously means when sending this request other request also be called at the same time. If this is false, other request are only be called after this request is complete.
Create Asp.Net Core Project
Open Visual Studio and click on create a new project.
Select Asp.net Core Web App with Model View Controller and click on next button. You can also select Asp.net core without MVC or empty project but you have to add libraries and layout yourself. But in this template model, view and controller folder are already created with the required libraries and layout file.
Enter your project name, location, and solution name and click on next button.
Select targeted framework and other information like authentication if required etc. and click on Create button.
Here I remove already created model, controller and its view. If you delete the existing controller, create new controller by right click on controller folder then Add>Controller.
Gave controller name and click on Add button.
Post Data without Form Serialize
Create an action method in controller.
Create a model class. To add a model class, right-click on Model folder, click on Add > Class.
Give an appropriate name to your model. Here I gave name as student to my model class.
Create properties in your model class.
Create a new action method which will be called from Ajax. As you see in below code, I create Post method named SaveStudentWithoutSerialize which takes Student model class as a parameter and return type is JSON.
Create view for appropriate to your requirement and model.
Explanation of View
- Here, I create fields according to my model class properties. For better understanding I added highly used component like textbox, radio button, drop down and checkbox.
- On button click event we will call SaveStudent function, in this function we will post data using Ajax
- You can see in below image how value stored in this object.
- The point to remember here is that give the same name of property that you gave to your model class.
- On success and error callback, we show alert to user.
- Click on Save button and will go to controller side and data is bound to student model and shown in below image. And message is returned to Ajax side which will show in alert.
Add Validation in Form and Post Data with Form Serialize
For showing validation in Asp.Net core we have to add data annotation to properties of our model class. For this section of article we are going to create new model class, action methods and also new view.
Create new model class with data annotation attributes. I’m going to make same properties as shown in above section. Here I gave Student1 name to my new class. With following properties. Here I used Required and Range data annotation. You can use as per your requirements.
Create new action method. Here I create a new action method called WithValidation as you can see in below code.
Create new post method which takes new class Student1 as parameter. As you see in the below code, I create a new method named SaveStudentWithSerialize. Return type is same as old method.
Create view as per your requirements.
Explanation of View
- Here, I create the same view as created in the above example.
- Main difference you noticed is that asp-for attribute is added in all fields and assign to its respective properties.
- Also added span with validation-for attribute which will show error message when any validation error occur.
- Foremost here I added two script from CDN. First is JQuery Validate and second one is JQuery Validate unobtrusive. JQuery Validate unobtrusive used to show validation at client side without submitting form. So here we can save time to make round trip to the server.
- In document ready event, I parse form element to JQuery Validate unobtrusive by form ID. When all the element is loaded in document JQuery Validate unobtrusive add special data attributes to all fields as per validation given in data annotation attributes as you can see in below image.
- In SaveStudent function first we check if all the fields value are as per our given validation or not if any error occur it will show in span tag otherwise it will go inside condition and execute rest of the script.
- For formData here we just serialize the form by its ID attribute rather than old way which we have shown in above method. Value is stored same as query string in this object as you see in below image
- Rest of Ajax call is same as we shown above.
You can download or access all these code from my GitHub.
Source: YogeshHadiya.in - How To Post Data To The Controller Using AJAX With Validations In ASP.NET Core