ASP.Net MVC
MVC:
Model is a data and business logic.
View is a User Interface.
Controller is a request handler.
The ValidationSummary helper method generates an unordered list
(ul element) of validation messages that are in the ModelStateDictionary object.
if excludePropertyErrors set true to have the summary display
model-level errors only, or false to have the summary display all errors.
Model is a data and business logic.
View is a User Interface.
Controller is a request handler.
ASP.NET MVC Folder Structure:
App_Data folder can contain application data files like LocalDB, .mdf files, xml files and other data related files. IIS will never serve files from App_Data folder.
Content folder contains static files like css files, images and icons files. MVC 5 application includes bootstrap.css, bootstrap.min.css and Site.css by default.
Global.asax allows you to write code that runs in response to application level events, such as Application_BeginRequest, application_start, application_error, session_start, session_end etc.
Packages.config file is managed by NuGet to keep track of what packages and versions you have installed in the application.
Web.config file contains application level configurations.
Routing in MVC :
ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match
Route: It is map to mvc contoller.
Routes are URL patterns that are used for processing requests and that can be used to construct URLs dynamically. The Routes property is a
static
property that contains all the routes in an application that are used to specify how a URL request is matched to a class that handles the request. To specify a route, you add the route definition to the Routes property. Typically, you add routes to the Routes property from an event handler for the Application_Start
event in the Global.asax file
When an ASP.NET application handles a request, the application iterates through the collection of routes in the Routes property to find the route that matches the format of the URL request.
The URL pattern is considered only after domain name part in the URL.
Route constraints use to restrict the browser requests that match a particular route. You can use a regular expression to specify a route constraint.
routes.MapRoute(
"Product",
"Product/{productId}",
new {controller="Product", action="Details"},
new {productId = @"\d+" }
);
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- The IgnoreRoute method ensures that any URLs that contain the file extension .axd are not processed by the routing engine.
- Normal ASP.NET handling will occur based on existing http handler mappings.
URL Rewriting:
When a client sends a request to the Web server for a particular URL, the URL rewriting module analyzes the requested URL and changes it to a different URL on the same server. The URL rewriting module runs early in the request-processing pipeline, modifying the requested URL before the Web server decides which handler to use to process the request. The handler, which is chosen based on the rewritten URL, processes the request and generates a response that is sent back to the Web browser. The requesting client never sees the rewritten URL; as far as the client is concerned, it has received a response from the original URL.
Attribute routing uses attributes to define routes. Attribute routing provides us more control over the URIs in your web application.
Enabling Attribute Routing: routes.MapMvcAttributeRoutes();
use [Route(“books/lang/{lang=en}”)]
Scaffolding is an automatic code generation framework for ASP.NET web applications. Scaffolding reduces the time taken to develop a controller, view etc. in MVC framework. You can develop a customized scaffolding template using T4 templates as per your architecture and coding standard.
Action method:
- Action method must be public. It cannot be private or protected
- Action method cannot be overloaded
- Action method cannot be a static method.
- By default, Index is a default action method for any controller,
Action Result :
The ActionResult class is a base class of all the above result classes, so it can be return type of action methods which returns any type of result listed below.
Result Class | Description |
---|---|
ViewResult | Represents HTML and markup. |
EmptyResult | Represents No response. |
ContentResult | Represents string literal. |
FileContentResult/ FilePathResult/ FileStreamResult | Represents the content of a file |
JavaScriptResult | Represent a JavaScript script. |
JsonResult | Represent JSON that can be used in AJAX |
RedirectResult | Represents a redirection to a new URL |
RedirectToRouteResult | Represent another action of same or other controller |
PartialViewResult | Returns HTML from Partial view |
HttpUnauthorizedResult | Returns HTTP 403 status |
Action Selector:
Action selector is the attribute that can be applied to the action methods. It helps routing engine to select the correct action method to handle a particular request.
ActionName attribute allows us to specify a different action name than the method name.
[ActionName("find")]
public ActionResult GetById(int id){}
NonAction selector attribute indicates that a public method of a Controller is not an action method.
The ActionVerbs selector is used when you want to control the selection of an action method based on a Http request method.
Multiple action verbs can be applied
using [AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]
Multiple Models in Single View in MVC:
Reference :https://www.c-sharpcorner.com/UploadFile/ff2f08
/multiple-models-in-single-view-in-mvc/
1. Using Dynamic Model:
public ActionResult Index() { ViewBag.Message = "Welcome to my demo!"; dynamic mymodel = new ExpandoObject(); mymodel.Teachers = GetTeachers(); mymodel.Students = GetStudents(); return View(mymodel); }
View :
@model dynamic
@foreach (Teacher teacher in Model.Teachers) { }
2. Using View Model :
public class ViewModel
{
public IEnumerable<Teacher> Teachers { get; set; }
public IEnumerable<Student> Students { get; set; }
}
public ActionResult IndexViewModel()
{
ViewBag.Message = "Welcome to my demo!";
ViewModel mymodel = new ViewModel();
mymodel.Teachers = GetTeachers();
mymodel.Students = GetStudents();
return View(mymodel);
}
3. Using ViewData :
public ActionResult IndexViewData()
{
ViewBag.Message = "Welcome to my demo!";
ViewData["Teachers"] = GetTeachers();
ViewData["Students"] = GetStudents();
return View();
}
on View need to cast.
4. Using ViewBag :
public ActionResult IndexViewBag()
{
ViewBag.Message = "Welcome to my demo!";
ViewBag.Teachers = GetTeachers();
ViewBag.Students = GetStudents();
return View();
}
5. Using Tuple
public ActionResult IndexTuple()
{
ViewBag.Message = "Welcome to my demo!";
var tupleModel = new Tuple<List<Teacher>, List<Student>>(GetTeachers(), GetStudents());
return View(tupleModel);
}
on View
@model Tuple <List<Teacher>, List <Student>>
@{
ViewBag.Title = "Home Page";
}
@foreach (Teacher teacher in Model.Item1)
{ }
6. Using Render Action Method .
Model Binding:
HttpGET request embeds data into a query string.Binding to Complex type :automatically converts form field data of HttpPOST request tothe properties of a complex type.FormCollection:FormCollection type parameter in the action method insteadof complex type. example :Public ActionResult edit(FormCollection value) { var name=value["keyName"]; }Bind Attribute:
The [Bind] attribute will let you specify the exact properties a model binder should include or exclude in binding.
[HttpPost]
public ActionResult Edit([Bind(Include = "StudentId, StudentName")] Student std)
{
var name = std.StudentName;
//write code to update student
return RedirectToAction("Index");
}
Default value provider collection evaluates values from the following sources:
- Previously bound action parameters, when the action is a child action
- Form fields (Request.Form)
- The property values in the JSON Request body (Request.InputStream), but only when the request is an AJAX request
- Route data (RouteData.Values)
- Querystring parameters (Request.QueryString)
- Posted files (Request.Files).
Razor Syntax:
Razor allows you to write mix of HTML and server side code using C# or Visual Basic.Inline expression:
Start with @ symbol to write server side C# .<h2>@DateTime.Now.ToShortDateString()</h2>
Multi-statement Code block :You can write multiple line of server side code enclosed in braces @{ ... }. Each line must ends with semicolon same as C#.
- Use @ to write server side code.
- Server side code block starts with @{* code * }
- Use @: or <text></<text> to display text from code block.
- if condition starts with @if{ }
- for loop starts with @for
- @model allows you to use model object anywhere in the view.
HTML Helpers:
HtmlHelper class generates html elements using the model class object in razor view. It binds the model object to html elements to display value of model properties into html elements and also assigns the value of the html elements to the model properties while submitting web form. So always use HtmlHelper class in razor view instead of writing html tags manually.
lHelper
Strogly Typed
HtmlHelpers
Html Control
Html.ActionLink
Anchor
link
Html.TextBox
Html.TextBoxFor
Textbox
Html.TextArea
Html.TextAreaFor
TextArea
Html.CheckBox
Html.CheckBoxFor
Checkbox
Html.RadioButton
Html.RadioButtonFor
Radio
button
Html.DropDownList
Html.DropDownListFor
Dropdown,
combobox
Html.ListBox
Html.ListBoxFor
multi-select
list box
Html.Hidden
Html.HiddenFor
Hidden
field
Password
Html.PasswordFor
Password
textbox
Html.Display
Html.DisplayFor
Html
text
Html.Label
Html.LabelFor
Label
Html.Editor
Html.EditorFor
Generates
Html controls based on data type of specified model property e.g.
textbox for string property, numeric field for int, double or
other numeric type.
Reference: http://www.tutorialsteacher.com/mvc/htmlhelper-textbox-textboxfor
Difference between TextBox and TextBoxFor1.@Html.TextBox() is loosely typed method whereas @Html.TextBoxFor()is a strongly typed (generic) extension method.2.TextBox() requires property name as string parameter where as TextBoxFor()requires lambda expression as a parameter.3.TextBox doesn't give you compile time error if you have specified wrongproperty name. It will throw run time exception.4.TextBoxFor is generic method so it will give you compile time error ifyou have specified wrong property name or property name changes.(Provided view is not compile at run time. )Data Validation in MVC:
ASP.NET MVC uses DataAnnotations attributes to implement validations. DataAnnotations includes built-in validation attributes for different validation rules, which can be applied to the properties of model class.The DataAnnotations attributes included in System.ComponentModel. DataAnnotations namespace.
attribute
|
Description
|
---|---|
Required
|
Indicates
that the property is a required field
|
StringLength
|
Defines
a maximum length for string field
|
Range
|
Defines
a maximum and minimum value for a numeric field
|
RegularExpression
|
Specifies
that the field value must match with specified Regular Expression
|
CreditCard
|
Specifies
that the specified field is a credit card number
|
CustomValidation
|
Specified
custom validation method to validate the field
|
EmailAddress
|
Validates
with email address format
|
FileExtension
|
Validates
with file extension
|
MaxLength
|
Specifies
maximum length for a string field
|
MinLength
|
Specifies
minimum length for a string field
|
Phone
|
Specifies
that the field is a phone number using regular expression for
phone numbers
|
MvcHtmlString ValidateMessage(bool excludePropertyErrors, string message, object htmlAttributes)
Use ValidationMessageFor or ValidationMessage helper method to display field level error messages in the view.
Layout View:
The layout view allows you to define a common site template, which can be inherited in multiple views to provide a consistent look and feel in multiple pages of an application. The layout view eliminates duplicate coding and enhances development speed and easy maintenance.You can set the layout view in multiple ways, by using _ViewStart.cshtml or setting up path of the layout page using Layout property in the individual view or specifying layout view name in the action method.
ViewStart.cshtml is included in the Views folder by default.
It sets up the default layout page for all the views in the folder
and its subfolders using the Layout property. You can assign a valid
path of any Layout page to the Layout property.
_ViewStart.cshtml can also be included in sub folder of View folder to set the default layout page for all the views included in that particular subfolder only.
Setting Layout property in individual view:
The @Html.RenderPartial helper method is same as the Partial method except that it returns void and writes resulted html of a specified partial view into a http response stream directly. RenderPartial returns void, so a semicolon is required at the end and so it must be enclosed in the braces.Layout = "~/Views/Shared/_myLayoutPage.cshtml";
Specify Layout Page in ActionResult Method:
public ActionResult Index() { return View("Index", "_myLayoutPage"); }
- The Layout view contains common parts of a UI. It is same like masterpage of ASP.NET webforms.
- _ViewStart.cshtml file can be used to specify path of layout page, which in turn will be applicable to all the views of the folder and its subfolder.
- You can set the Layout property in the individual view also, to override default layout page setting of _ViewStart.cshtml
- Layout view uses two rendering methods: RenderBody() and RenderSection().
- RenderBody can be used only once in the layout view, whereas the RenderSection method can be called multiple time with different name.
- RenderBody method renders all the content of view which is not wrapped in named section.
- RenderSection method renders the content of a view which is wrapped in named section.
- RenderSection can be configured as required or optional. If required, then all the child views must included that named section.
Partial View:
Partial view is a reusable view, which can be used as a child view in multiple other views. It eliminates duplicate coding by reusing same partial view in multiple places.
If a partial view will be shared with multiple views of different controller folder then create it in the Shared folder, otherwise you can create the partial view in the same folder where it is going to be used.
Render Partial View:
@Html.Partial() helper method renders the specified partial view. It accept partial view name as a string parameter and returns MvcHtmlString. It returns html string so you have a chance of modifing the html before rendering.
The @Html.RenderAction helper method invokes a specified controller and action and renders the result as a partial view. The specified Action method should return PartialViewResult using the Partial() method.
ViewBag:
- ViewBag transfers data from the controller to the view, ideally temporary data which in not included in a model.
- ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
- You can assign any number of propertes and values to ViewBag. If you assign the same property name multiple times to ViewBag, then it will only consider last value assigned to the property.
- The ViewBag's life only lasts during the current http request. ViewBag values will be null if redirection occurs.
- ViewBag is actually a wrapper around ViewData.
ViewData:
- ViewData transfers data from the Controller to View, not vice-versa.
- ViewData is derived from ViewDataDictionary which is a dictionary type.
- ViewData's life only lasts during current http request. ViewData values will be cleared if redirection occurs.
- ViewData value must be type cast before use.
- ViewBag internally inserts data into ViewData dictionary. So the key of ViewData and property of ViewBag must NOT match.
TempData:
Keep(): Marks all keys in the dictionary for retention. Keep(String): Marks the specified key in the dictionary for retention.
- TempData can be used to store data between two consecutive requests. TempData values will be retained during redirection.
- TemData is a TempDataDictionary type.
- TempData internaly use Session to store the data. So think of it as a short lived session.
- TempData value must be type cast before use. Check for null values to avoid runtime error.
- TempData can be used to store only one time messages like error messages, validation messages.
- Call TempData.Keep() to keep all the values of TempData in a third request.
The keep() and peek() method is used to read the data without deletion the current read object.You can use Peek() when you always want to hold/prevent the value for another request. You can use Keep() when prevent/hold the value depends on additional logic.Overloading in TempData.Peek() & TempData.Keep() as given below.TempData.Keep() have 2 overloaded methods.
void keep() : That menace all the data not deleted on current request completion. void keep(string key) : persist the specific item in TempData with help of name.TempData.Peek() no overloaded methods.
- object peek(string key) : return an object that contain items with specific key without making key for deletion.
Filters :ASP.NET MVC provides feature to add pre and post action behaviors on controller's action methods.
https://www.c-sharpcorner.com/UploadFile/8ef97c/most-asked-Asp-Net-mvc-interview-questions-and-answers/
- Action Filters: Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter.
- Authorization Filters: Authorization filters are used to implement authentication and authorization for controller actions.
- Result Filters: Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
- Exception Filters: Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You can also use exception filters to log errors.
Action filters are one of most commonly used filters to perform additional data processing, or manipulating the return values or cancelling the execution of action or modifying the view structure at run time.
Comments
Post a Comment