ASP NetMVC Core Working With Data Create Form StronglyTyped
ASP.NET Core MVC: Creating a Strongly Typed Data Form
In this blog post, we will explore how to create a strongly typed data form in ASP.NET Core MVC. This tutorial is based on the video titled "ASP NetMVC Core Working With Data Create Form StronglyTyped." By the end of this guide, you will have a clear understanding of how to build a simple form that captures user input, validates it, and processes the data on the server side.
What is ASP.NET Core MVC?
ASP.NET Core MVC is a framework for building web applications using the Model-View-Controller architectural pattern. It enables developers to create dynamic web applications that can handle user input, manage data, and render views efficiently. A key feature of ASP.NET Core MVC is strong typing, which enhances type safety and reduces runtime errors.
Prerequisites
Before we dive into the tutorial, ensure you have the following prerequisites:
- Visual Studio 2019 or later
- .NET Core SDK installed
- Basic knowledge of C# and HTML
- Familiarity with the MVC architecture
Getting Started
Step 1: Create a New ASP.NET Core MVC Project
- Open Visual Studio and select "Create a new project."
- Choose "ASP.NET Core Web Application" and click "Next."
- Name your project (e.g.,
StronglyTypedForm) and select a location. Click "Create." - Select the "Web Application (Model-View-Controller)" template and ensure that "Enable Docker" is unchecked. Click "Create."
Step 2: Define the Model
Models represent the data structure of your application. In this example, we will create a simple model to capture user information.
- Right-click on the
Modelsfolder in the Solution Explorer and select Add > Class. - Name the class
UserInfo.csand define the properties as follows:
using System.ComponentModel.DataAnnotations;
namespace StronglyTypedForm.Models
{
public class UserInfo
{
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
[Required(ErrorMessage = "Email is required.")]
[EmailAddress(ErrorMessage = "Invalid email format.")]
public string Email { get; set; }
[Required(ErrorMessage = "Age is required.")]
[Range(1, 120, ErrorMessage = "Age must be between 1 and 120.")]
public int Age { get; set; }
}
}
Step 3: Create the Controller
Next, we will create a controller to handle the form submission.
- Right-click the
Controllersfolder and select Add > Controller. - Choose "MVC Controller - Empty" and name it
UserInfoController.
In the UserInfoController.cs, add the following code:
using Microsoft.AspNetCore.Mvc;
using StronglyTypedForm.Models;
namespace StronglyTypedForm.Controllers
{
public class UserInfoController : Controller
{
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(UserInfo userInfo)
{
if (ModelState.IsValid)
{
// Process the data (e.g., save to database)
return RedirectToAction("Success");
}
return View(userInfo);
}
public IActionResult Success()
{
return View();
}
}
}
Step 4: Create the Create View
Now, we will create a view for our Create action to display the form.
- Right-click the
Viewsfolder, then right-click on theUserInfofolder and select Add > View. - Name the view
Create.cshtmland use the following code:
@model StronglyTypedForm.Models.UserInfo
<h2>Create User Info</h2>
<form asp-action="Create" method="post">
<div>
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div>
<label asp-for="Email"></label>
<input asp-for="Email" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div>
<label asp-for="Age"></label>
<input asp-for="Age" type="number" />
<span asp-validation-for="Age" class="text-danger"></span>
</div>
<button type="submit">Submit</button>
</form>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Step 5: Create the Success View
Lastly, let’s create the success view to display a message after form submission.
- Again, right-click on the
UserInfofolder and select Add > View. - Name the view
Success.cshtmland add the following code:
<h2>Submission Successful!</h2>
<p>Your information has been submitted successfully.</p>
Step 6: Update Startup.cs
To enable validation scripts and MVC features, make sure your Startup.cs is configured correctly.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=UserInfo}/{action=Create}/{id?}");
});
}
Step 7: Run Your Application
With everything set up, run your application. You should be able to access the form at https://localhost:{port}/UserInfo/Create. Fill out the form and submit it. If the input is valid, you will be redirected to the success page.
Conclusion
In this tutorial, we created a strongly typed data form in ASP.NET Core MVC. We defined a model, created a controller to handle the form, and built a view to capture user input. This approach not only enhances type safety but also simplifies validation and error handling.
Feel free to expand this basic example by adding more fields, integrating with a database, or implementing additional features. Happy coding!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment