
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialProgramming
4.8 Rating 34 Questions 25 mins read7 Readers

MVC architecture represents the domain-specific data and business logic. It maintains the data of the application, model data hold the data in public property.
We can also manipulate the data in the business logic layer
Namespace mvc.Models
{
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
}In Model, we can apply validation to the property using Data Annotation instead of applying on the client side. For adding data Annotation we need to add the reference “System.ComponentModel.DataAnnotations assembly”
Like we apply on StudentId
Eg.
[Display(Name=”StudentId ”)]
[Required(ErrorMessage=”StudentId is Required”)]
Public int StudenId {get;set;}View : View is the User Interface where The user can display its own data and can modify its data, In this, the data is passed from the model to the view. The view has a different folder with the same name as of controller and has different views in it of different actions.
There are 3 types of Views in MVC
Controller: It is the most essential part of the MVC in asp.net since it is the first recipient which interacts with HTTP and finds the model and actions. So it is the controller which decides which model should be selected and how to carry the data from the respective view, a controller is inherited from the System.Mvc.Controller. The routing map of the controller is decided in RouteConfig.cs which is under App Start Folder.
Eg, http://localhost:61465/Employee/Mark
Where Employee is a controller name and mark is the action.
The advantages of MVC of ASP.NET are :
Razor is not a programming language but an HTML markup language which is written on the server side using C#. Razor does not have the tie-up with Asp.net mvc. It has implemented a view engine to use razor view to produce the HTML output. It uses the @{....} syntax. It uses a semicolon to end the statement, it has .cshtml as file extensions.inline expression also uses the @ expression’
Conditions with if statement
It starts with a code block and its condition is written in parenthesis. the code which needs to be executed is written inside braces.
@{var Price=60;}
<html>
<body>
<if(Price>60)
{
<p>This is paragraph</p>
}
</body>
</html>In the above example, we have declared var price has a value of 60 and we are using if statement which is validating price. the code written in side braces gets executed,if price value is greater than 50.
In razor, we have a different type of block statements available, which are
1.Single Statement Block and Inline Expression: It is the same as we discussed above that it is the block of code which is executed in the single line statement.
@{var series=4;}
<p>MVC series :@series</p>
<p>Razor Message:@RazorMessage</p>2.Multiple Statement Block with Inline Expressions : In this we declare all the variable in single @{....} and each variable is ended with the semi colon
@{
Var a =”This is Razor Syntax”;
Var b = DateTime.Now.DayOfWeek;
Var c = a + “Date on ”+b;
}
<p>Razor Message:@HomeMessage</p>So it is better to declare the variable at the top of the view because if we declare the variable at the top then it can be used in all inline block of statement written on that view and if we declare this variable at the middle order of view then we cannot use at the top statement written in @{....}.
This is one of the most frequently asked MVC interview questions for freshers and experienced in recent times.
When a programmer send the request and when it goes to the action method it sees the return type of the action result and produces the desired result on the view after that,
Action Result is a result of action methods or return types of action methods. Action result is an abstract class.
Different types of ActionResult are-
1.View Result: View Result is very simple Action Result type it is a class which is derived from the ViewResultBase class and viewResultBase Class is derived from the ActionResult, View results in the data in view which is defined in the model. View page is a simple HTML page. Here view page has “.cshtml” extension
Eg,
Public ViewResult About()
{
ViewBag.Message=”The View Result is here”;
Return View();
}2.Partial View Result : The partial view is a class which is also derived from action result class. When we create a partial view it is created in the shared folder with the .cshtml extensions. If we don't have the partial view we cannot access the partial view, Partial view is one of the views that we can call inside the Normal view page.
Eg.
public partialViewResult Index()
{
Return PartialView(“_PartialView”);
}3.Render Result: it helps in redirecting the request to the specific url ,if the url is wrong then it gives the Error 404
Eg
public RedirectResult Index()
{
return Redirect("Home/Contact");
}4.Redirect to Action Result: it helps in redirecting the request to action through the controller it is not necessary to mention the controller name in RedirectToAction() if controller is not there then it will redirected to the action which matches in RedirectToAction() ,if action does not find on the page then it will give the error 404.
public ActionResult Index()
{
return RedirectToAction("Login", "Account");
}5.Json Result : Json result is a significant Action Result in MVC. It will return response in the format of key value pairs.it return json if we call json method
Eg:
Public ActionResult Index()
{
var persons = new List<Person1>
{
new Person1
{
Id=1, FirstName="Harry", LastName="Potter"
},
new Person1
{
Id=2, FirstName="James", LastName="Raj"
}
};
return Json(persons, JsonRequestBehavior.AllowGet);
}ViewData:ViewData is used when we want to transfer the data from controller to view it as a dictionary which is used to transfer the data in the form of key-value pair where key is always string, we can transfer the data from the controller to view but it is not possible to transfer the data from view to controller using ViewData.
Eg,
ActionResult Index()
{
IList<Student> studentList = new List<Student>();
studentList.Add(new Student(){ StudentName = "Bill" });
studentList.Add(new Student(){ StudentName = "Steve" });
studentList.Add(new Student(){ StudentName = "Ram" });
ViewData["students"] = studentList;
return View();
}Access ViewData in a Razor View
<ul>
@foreach (var std in ViewData["students"] as IList<Student>)
{ <li> @std.StudentName </li>
}
</ul>Add KeyValuePair in ViewData
public ActionResult Index()
{
ViewData.Add("Id", 1);
ViewData.Add(new KeyValuePair<string, object>("Name", "Bill")); ViewData.Add(new KeyValuePair<string, object>("Age", 20));
return View();
}Viewdata request is last till the current web request, it the cleared the view data when there is the redirection, before using the viewdata we need to cast it. We can use the temp data in MVC 1.0 and its above version.it requires the type conversion while we are enumerating. It will throw the error when there is the redirection of a request.
ViewBag : ViewBag is used to when we want to transfer the small amount of data from Controller to view or we can say when we want to transfer temporary data (which is not included in model) from the controller to the view.its derived from the controller base Class which is a base class for all the controller,it attaches the name property with dot notation and assign the string value in it and using razor syntax @ to get the server side code,
You can assign any number of properties and values to ViewBag. What so ever time you will assign the values to the viewbag it will consider the last value defined in the property.
namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
IList<Student> studentList = new List<Student>()
{
new Student()
{
StudentID=1, StudentName="Steve", Age = 21
},
new Student()
{
StudentID=2, StudentName="Bill", Age = 25
},
new Student()
{
StudentID=3, StudentName="Ram", Age = 20
},
new Student()
{
StudentID=4, StudentName="Ron", Age = 31
},
new Student()
{
StudentID=5, StudentName="Rob", Age = 19
}
}; // GET: Student
public ActionResult Index()
{
ViewBag.TotalStudents = studentList.Count();
return View();
}
}
}On view page we can access the data by
<label>Total Students:</label> @ViewBag.TotalStudents
TempData: ASP.NET MVC can be used to store temporary data which can be used in the subsequent request.it is very useful when we want to transfer the data from one action to another action or from one controller to another controller, the data is passed in the form of key-value pair
public class HomeController : Controller
{ // GET: Student
public HomeController()
{
}
public ActionResult Index()
{
TempData["name"] = "Test data";
TempData["age"] = 30;
return View();
}
public ActionResult About()
{
string userName;
int userAge;
if(TempData.ContainsKey("name"))
userName=TempData["name"].ToString(); if(TempData.ContainsKey("age"))
userAge = int.Parse(TempData["age"].ToString());
return View();
}
}Life span for temp data is very small. Data in TempData can persist only upto next view or upto next controller action. If we want to take data in TempData to successive requests then we need to call a method: TempData.Keep(), to keep the data persists for next request.
Expect to come across this, one of the most important MVC interview questions for experienced professionals in programming, in your next interviews.
ASP.NET MVC has provided ViewBag and ViewData to transfer data from the controller to view. Let’s look into these in deep:
ViewData: ViewData is derived from the ViewDataDictionary, hence it stores data in key Value format like a dictionary, where the Keys are in String and represents the name of an object while Values will be objects. As data in ViewData is stored in object form, so it is required to cast the data to its original type before using it. It is also required to do the NULL check while retrieving data. The life span of ViewData is from Controller to View.
Example: ViewData["Message"] = "Test Data";
ViewBag: ViewBag is a Wrapper that is built around the ViewData. It is a dynamic property and it makes use of the C# 4.0 dynamic features. Like ViewData, it is not required to do typecasting data before use. The life span of ViewBag is from Controller to View only.
Example: ViewBag.Message = "Test Data";
TempData: TempData is derived from TempDataDictionary class and it is also a Dictionary object i.e. Keys and Values where Keys are in String and represents the name of the object while Values will be objects. It is required to do typecasting of data before using it as the data is in the object format and it also requires NULL checks while retrieving. The life span of TempData is larger than of ViewData and ViewBag. TempData can be used for passing value from Controller to View and from Controller to Controller. It is also available for Current and Subsequent Requests.
Example: TempData["Message"] = "Test temp data";
The base type for all the return types of action method is “Action Result”. Below are the various return types that can be used to return results from a controller action method.
ASP.NET MVC 2 introduced Area. It allows us to partition the large application into smaller units/folders where folder unit contains separate MVC folder structure, same as default MVC folder structure. For example, big enterprise applications can have different modules like admin, finance, HR, marketing, etc. So an Area can contain separate MVC folder structure for all these modules.
Areas are basically the logical grouping of Controller, Models and Views and other related folders for a module in MVC applications. Using areas helps to write more maintainable code for an application cleanly separated according to the modules.
Benefits of Area in MVC
Routing is the way to locate the action that matches the URI in ASP.NET MVC. Sometimes it is required to have a route that is different in pattern from other routers in the application and is not possible to configure it by making use of convention-routing.
In MVC 5, a new type of routing is introduced, called attribute routing. Attribute Routing has given more flexibility to configure routes that are specific to any controller/action. Like the name says, routes are added as an attribute to controller/action. This type of routing provides you more control over the URIs in your web application.
Example of Attribute Routing:
[Route(“{category:int}/{categoryName}”)]
public ActionResult Show(int categoryId) { … }To enable attribute routing, call MapMvcAttributeRoutes during configuration.
Route Prefixes:
Route Prefixes are the prefix for any route that we want to apply, this is done by defining the route prefix on a controller so that all the action methods inside it can follow the prefix.
[RoutePrefix("category")]
public class CategoryController : Controller
{ .... }Like in ASP.Net web forms, we have a toolbox for adding controls (like textbox, label, dropdown) on any particular page. Now, in the ASP.NET MVC application, there is no toolbox available to add controls on the view. ASP.NET MVC provides HtmlHelper class which contains various methods that help you create HTML controls programmatically. All HtmlHelper methods generate HTML and return the result as a string. The final HTML is generated at runtime by these functions. The HtmlHelper class is designed to generate UI and it should not be used in controllers or models.
The following is the list of Html Helper controls.
Html.Beginform
Html.EndForm
Html.Label
Html.TextBox
Html.TextArea
Html.Password
Html.DropDownList
Html.CheckBox
Html.RedioButton
Html.ListBox
Html.Hidden
Below are Strongly Type Html Helper methods, this will allow us to check compile-time errors.
We get Model's Property intelligence at Runtime.
Html.LabelFor
Html.TextBoxFor
Html.TextAreaFor
Html.DropDownListFor
Html.CheckBoxFor
Html.RadioButtonFor
Html.ListBoxFor
Html.HiddenFor
HtmlHelper class generates html elements. For example, @Html.ActionLink("Create New", "Create") would generate anchor tag <a href="/Student/Create">Create New</a>.
A staple in Spring MVC interview questions for experienced professionals, be prepared to answer this one using your hands-on experience.
Unobtrusive javascript library allows to add validation to MVC views without any additional coding, only required to use attributes like RequiredAttribute, RangeAttribute and include the correct script files.
Example:
public class AddUserVM
{
[DisplayName("First Name:")]
[Required(ErrorMessage = "Please enter the first name.")]
public string FirstName { get; set; }
[DisplayName("Last Name:")]
[Required(ErrorMessage = "Please enter the last name.")]
public string LastName { get; set; }
[DisplayName("Age:")]
[Range(12, 120, ErrorMessage = "You must be between 12 and 120 years of age.")]
public int Age { get; set; }
[DisplayName("Email:")]
[Required(ErrorMessage = "Please enter an email address.")]
[EmailAddress(ErrorMessage = "Please enter a valid email address.")]
public string EmailAddress { get; set; }
}The above class setup is to handle the server side validations. Unobtrusive validations allow us to take existing validation attributes and use them at client-side to make the user experience much better.
Routing enables us to define a URL pattern that maps to the request handler.in asp.net request handler is .aspx file while in MVC request handler is controller and actions. All the route of the application is stored in RouteTable and the Routing engine helps in finding the appropriate handler class for the request, when the request and goes to the route table if it finds the appropriate actions and controller and give the response and if it doesn`t find the controller and actions it will give the Error 404.
When we create the MVC application it creates one route by default which is defined under RouteConfig.cs file under AppStart Folder
Eg- public class RouteConfig
{
Public static void RegisterRoutes(RouteCollection Routes)
{
routes,MapRoutes(name:”Deafult”,”
url : “{controller}/{actions}/{id}”,
deafults:new {controller=”Home”,action=”Index”,id=UrlParameter.Optional});
}
}As we have seen in above that in Maproute() extension method of the route collection, where the name is default, URL pattern is “{controller}/{action}/{id}" Defaults specify which controller, action method or value of id parameter should be used if not present in the incoming request URL. the main content of the URL is after the domain name localhost:1234/{controller}/{action}/{id}.
Where localhost:1234 is the domain name, if the URL doesn't contain anything after the domain then the default request i.e Home as a controller and the Index as a view will handle the request
We can also configure a custom route using MapRoute extension method. We need to provide at least two parameters in MapRoute, route name, and a URL pattern. The Defaults parameter is optional.
Eg- public class RouteConfig
{
Public static void RegisterRoutes(RouteCollection Routes)
{
routes,Map Routes(
name:”Default”,
url:”{controller}/{actions}/{id}”,
defaults:new {controller=”Home”,action=”Index”,id=UrlParameter.Optional});
routes,Map Routes(
name:”Students”,
url:”Students/{id}”,
defaults:new {controller=”Students”,action=”Index”l});
}
}In the above example, there is a custom route where controller name is Students and since there is no such action defined in the URL so the default action is an index for all the actions belongs to the controller class.
When we want to be executed just prior to the action execution, when the user sends the request to the controller, in this the user create the custom class which works as a filter where the developer writes the logic which will be implemented just prior to the action execution, By programming method we can apply filters to the actions ,There are different type of filter use in MVC :
When there is any kind of exception in an application then the exception filter executes. HandleErrorAttribute ([HandlerError]) class is a built-in exception filter class in MVC framework. The HandleErrorAttribute class renders Error.cshtml which is inside the shared folder which is added by default during project creation when an unhandled exception occurs.
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
throw new Exception("This is unhandled exception");
return View();
}
public ActionResult About()
{ return View();
}
public ActionResult Contact()
{
return View();
}
}A must-know for anyone looking for top MVC interview questions, this is one of the frequently asked MVC behavioral interview questions.
Html helper class helps when we want to show the property of the modal class into the view we use HTML helper class also when we want the values from the HTML input method parameter into the modal property we use HtmlHelper, HtmlHelper class generates HTML elements using the model class object in razor view.
Eg.
<p> @Html.ActionLink(“Create New”,”Create”) </p>
@Html is an object of HtmlHelper class. (We can access a server-side object in razor syntax by using @ symbol).it is a property which is included in the base class of razor view WebViewPage. ActionLink() and DisplayNameFor() is extension methods included in HtmlHelper class, HTML is a property that we inherit from the ViewPage base class. So, it's available in all of our views and it returns an instance of a type called HTML Helper.
“HTML.BeginForm” writes an opening Form Tag. It also ensures that the method is going to be “Post” when the user clicks on the “Save” button.
Html.Beginform is very helpful as it helps us in changing the Url and helps us in changing the methods, The Html.LabelFor HTML Helper creates the labels on the screen. If we entered something wrong then it will display the error using Html.ValidationMessageFor .
There are lots of benefits:
It has overloaded methods to pre-populate the values (formatted, and safe for HTML) just like the ViewState.
It allows you to override the rendering by providing your own DLL for changing the rendering (a sort of "Controller Adapter" type methodology).
In ASP.NET MVC data Annotation are built in validation which is applied on the modal class property and render it on the view in the validation summary
The DataAnnotations attributes included in System.ComponentModel.DataAnnotations namespace
Different types of data annotations are :
Eg.
public class Student
{
public int StudentId { get; set; }
[Required]
public string StudentName { get; set; }
[Range(5,50)]
public int Age { get; set; }
}In the above-stated example, we have the Required data annotation which implies that this field must be required in every scenario if the user left this modal property empty then it will give the default error message. In the same way, we can use the range to find the age property. This will validate and display an error message if the user has either not entered Age or entered an age less than 5 or more than 50.
Eg.
namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
public ActionResult Edit(int id)
{
var std = studentList.Where(s => s.StudentId == StudentId) .FirstOrDefault();
return View(std);
}
[HttpPost]
public ActionResult Edit(Student std)
{
if (ModelState.IsValid)
{ //write code to update student return RedirectToAction("Index"); }
return View(std);
}
}
}In this Modal State will check whether the data is valid is true and it will update in the database and if not then it will return the same data in the Edit View
ModelState.IsValid determines that whether submitted values satisfy all the DataAnnotation validation attributes applied to model properties.
Eg In the View the Data Annotation for the modal property will look like this
<div class="form-group">
@Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" })
</div>
</div>The validation Summary helper method will display the error message, ValidationMessageFor is responsible to display an error message for the specified field.