European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFEASP.NET :: Creating AutoComplete TextBox In ASP.NET MVC 5

clock December 8, 2021 08:20 by author Peter

One year back I wrote the following article: Creating AutoComplete Extender using ASP.NET  which has huge response. Currently it has 32 k views. So by considering same requirement in ASP.NET MVC I decided to write same type of article using ASP.NET MVC with the help of jQuery UI library. So let us implement this requirement step by step,

Step 1 - Create an ASP.NET MVC Application.
    "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
    Choose MVC empty application option and click on OK

Step 2 - Add model class.

Right click on Model folder in the created MVC application and add class named City and right the following line of code,

City.cs
    public class City  
      {  
          public int Id { get; set; }  
          public string Name { get; set; }  
      
      }


Step 3 Add user and admin controller
Right click on Controller folder in the created MVC application and add the controller class as,

Now after selecting controller template, click on add button then the following window appears,

Specify the controller name and click on add button, Now open the HomeController.cs file and write the following code into the Home controller class to bind and create the generic list from model class as in the following,

HomeController.cs
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web.Mvc;  
    using AutoCompleteInMVCJson.Models;  
    namespace AutoCompleteInMVCJson.Controllers  
    {  
        public class HomeController : Controller  
        {  
            // GET: Home  
            [HttpGet]  
            public ActionResult Index()  
            {  
                return View();  
            }  
            [HttpPost]  
            public JsonResult Index(string Prefix)  
            {  
                //Note : you can bind same list from database  
                List<City> ObjList = new List<City>()  
                {  
      
                    new City {Id=1,Name="Latur" },  
                    new City {Id=2,Name="Mumbai" },  
                    new City {Id=3,Name="Pune" },  
                    new City {Id=4,Name="Delhi" },  
                    new City {Id=5,Name="Dehradun" },  
                    new City {Id=6,Name="Noida" },  
                    new City {Id=7,Name="New Delhi" }  
      
            };  
                //Searching records from list using LINQ query  
                var Name = (from N in ObjList  
                                where N.Name.StartsWith(Prefix)  
                              select new { N.Name});  
                return Json(Name, JsonRequestBehavior.AllowGet);  
            }  
        }  
    }

In the above code, instead of going to database for records we are creating the generic list from model class and we will fetch records from above generic list.

Step 4
Reference jQuery UI css and js library reference as there are many ways to add the reference of jQuery library into the our project. The following are some methods:

    Using NuGet package manager , you can install library and reference into the project
    Use CDN library provided by Microsoft, jQuery, Google or any other which requires active internet connection.
    Download jQuery files from jQuery official website and reference into the project.

In this example we will use jQuery CDN library.

Step 5
Create jQuery Ajax function to call controller JSON action method and invoke autocomplete function,
    $(document).ready(function () {  
           $("#Name").autocomplete({  
               source: function(request,response) {  
                   $.ajax({  
                       url: "/Home/Index",  
                       type: "POST",  
                       dataType: "json",  
                       data: { Prefix: request.term },  
                       success: function (data) {  
                           response($.map(data, function (item) {  
                               return { label: item.Name, value: item.Name};  
                           }))  
      
                       }  
                   })  
               },  
               messages: {  
                   noResults: "", results: ""  
               }  
           });  
       })


To work above function don't forget to add the reference of the following jQuery CDN library as,
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">  
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>  
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

Step 6
Add view named index and put above json function into the view. After adding code necessary files and logic the Index.cshtml will look like the following,

Index.cshtml
    @model AutoCompleteInMVCJson.Models.City  
    @{    
        ViewBag.Title = "www.hostforlife.eu";    
    }    
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">    
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>    
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>    
    <script type="text/javascript">    
        $(document).ready(function () {    
            $("#Name").autocomplete({    
                source: function (request, response) {    
                    $.ajax({    
                        url: "/Home/Index",    
                        type: "POST",    
                        dataType: "json",    
                        data: { Prefix: request.term },    
                        success: function (data) {    
                            response($.map(data, function (item) {    
                                return { label: item.Name, value: item.Name};    
                            }))    
        
                        }    
                    })    
                },    
                messages: {    
                    noResults: "", results: ""    
                }    
            });    
        })    
    </script>    
    @using (Html.BeginForm())    
    {    
        @Html.AntiForgeryToken()    
        
        <div class="form-horizontal">    
        
            <hr />    
        
            <div class="form-group">    
        
                <div class="col-md-12">    
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })    
        
                </div>    
            </div>    
        
        </div>    
    }    


Now run the application and type any word then it will auto populate the records which exactly start with first word as in the following screenshot,

If you want to auto populate the records which contain any typed alphabet,then just change the LINQ query as contain. Now type any word it will search as follows,

From all the above examples, I hope you learned how to create the auto complete textbox using jQuery UI in ASP.NET MVC.

Note

    For the detailed code, please download the sample zip file.
    Perform changes in Web.config file as per your server location.
    You need to use the jQuery library.

For all the examples above, we learned how to use jQuery UI to create auto complete textbox in ASP.NET MVC. I hope this article is useful for all readers. If you have a suggestion then please contact me.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: OAuth Token Based Authentication In ASP.Net Identity

clock November 30, 2021 06:17 by author Peter

In this article, I will explain how to generate 'Access Token' using credentials of 'Asp.net Identity' in 'ASP.Net MVC. Create a new project in Visual Studio.

Give connection string of your database. Register an Account.

Add the following three Nuget Packages to your project.

  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Security.OAuth
  • Microsoft.Owin.Cors

Now, add TokenGenerating.cs class in the project.

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;

namespace SecureWebAPI.APIClasses
{
    public class TokenGenerating : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated(); //
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
            var result = userManager.Find(context.UserName, context.Password);
            //UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
            //var result = userManager.Find(context.UserName, context.Password);
            //UserManager holds data for register user.
            //context.UserName = Email of your registered user
            //context.Password = Password of your registered user
            if (result != null)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Provided username and password is incorrect");
                return;
            }
        }
    }
}

Now add a new startup class for the token configuration file this class holds the information and setting of the token.

using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Threading.Tasks;
using System.Web.Http;

[assembly: OwinStartup(typeof(SecureWebAPI.APIClasses.AuthenticationStartupClass))]

namespace SecureWebAPI.APIClasses
{
    public class AuthenticationStartupClass
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            var myProvider = new APIAUTHORIZATIONSERVERPROVIDER();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
        }
    }
}

Add new class for API Attributes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SecureWebAPI.APIClasses
{
    public class APIAUTHORIZEATTRIBUTE : System.Web.Http.AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                base.HandleUnauthorizedRequest(actionContext);
            }
            else
            {
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
            }
        }
    }
}

Change Global.asax file of your project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace SecureWebAPI
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configuration.EnsureInitialized();
        }
    }
}

Now change your WebApiConfig.cs file routemap

Your Project > App_Start folder > WebApiConfig.cs
routeTemplate: "api/{controller}/{action}/{id}",
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SecureWebAPI.Controllers
{
    public class UserController : ApiController
    {
        [AllowAnonymous]
        [HttpGet]
        public IHttpActionResult Get()
        {
            return Ok("Now server time is: " + DateTime.Now.ToString());
        }
        [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAuthenticate()
        {
            return Ok("Hello ");
        }
        [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAdmin()
        {
            return Ok("Helo User");
        }
    }
}

Add a ApiController .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SecureWebAPI.Controllers
{
    public class UserController : ApiController
    {
        [AllowAnonymous]
        [HttpGet]
        public IHttpActionResult Get()
        {
            return Ok("Now server time is: " + DateTime.Now.ToString());
        }
        [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAuthenticate()
        {
            return Ok("Hello ");
        }
        [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAdmin()
        {
            return Ok("Helo User");
        }
    }
}

Run your Project and leave it. Open Visual Studio, add a new console project. Add a new class to the console project.
class TokenInfo
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
}

Add function in Program.cs class.
public string GetAccessToken(string Email, string Password)
{
    string AccessToken = "";
    string responseFromServer = "";
    WebRequest request = WebRequest.Create("https://localhost:44370/token"); //your project url
    request.Method = "POST";
    string postData = "username=" + Email + "&password=" + Password + "&grant_type=password";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = byteArray.Length;
    System.IO.Stream dataStream = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();
    WebResponse response = request.GetResponse();
    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
    using (dataStream = response.GetResponseStream())
    {
        System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
        responseFromServer = reader.ReadToEnd();
        Console.WriteLine(responseFromServer);
    }
    TokenInfo myDeserializedClass = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenInfo>(responseFromServer);
    AccessToken = myDeserializedClass.access_token;

    response.Close();
    return AccessToken;
}

MainMethod
static void Main(string[] args)
{
    string Email = "Your Registered user Email";
    string Password = "Your Registered user Email";

    Program cls = new Program();
    string AccessToken = cls.GetAccessToken(Email, Password);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://localhost:44370/api/user/GetForAuthenticate"); //Your project Local host api url
    request.AutomaticDecompression = DecompressionMethods.GZip;
    request.Method = "GET";
    request.Headers.Add("Authorization", "Bearer " + AccessToken);
    using (System.Net.WebResponse GetResponse = request.GetResponse())
    {
        using (System.IO.StreamReader streamReader = new System.IO.StreamReader(GetResponse.GetResponseStream()))
        {
            dynamic jsonResponseText = streamReader.ReadToEnd();
        }
    }
    Console.ReadLine();
}

Run console project
If Credential is authenticated then an access token will also be generated.

Keep in mind Your Asp.net MVC project should be running during access token generating.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How To Implement AutoMapper In ASP.NET Core MVC Application?

clock November 23, 2021 06:04 by author Peter

In this demo, I will show how to utilize the Automapper library efficiently. Automapper makes our lives easy with minimal steps. In a nutshell, AutoMapper is an object-object mapper. It transforms the input object of one type into an output object of another type.

Requirements
    Visual Studio 2017.
    Auto Mapper NuGet Package
    Auto Mapper Dependency Injection Package

In this example, I’ve taken two classes, Employee and EmployeeModel.
    namespace ASPNETCORE_AUTOMAPPER.Models {  
        public class Employee {  
            public int Id {  
                get;  
                set;  
            }  
            public string Name {  
                get;  
                set;  
            }  
            public string Designation {  
                get;  
                set;  
            }  
            public string City {  
                get;  
                set;  
            }  
            public string State {  
                get;  
                set;  
            }  
        }  
    }  
    namespace ASPNETCORE_AUTOMAPPER.Models {  
        public class EmployeeModel {  
            public int Id {  
                get;  
                set;  
            }  
            public string Name {  
                get;  
                set;  
            }  
            public string Designation {  
                get;  
                set;  
            }  
            public Address Address {  
                get;  
                set;  
            }  
        }  
        public class Address {  
            public string City {  
                get;  
                set;  
            }  
            public string State {  
                get;  
                set;  
            }  
        }  
    }  

We are getting Employee object from the end user and trying to assign it to EmployeeModel with each property like below, which is a tedious job and in real time scenarios, we may have plenty of properties as well as complex types. So this is an actual problem.
    [HttpPost]  
    public EmployeeModel Post([FromBody] Employee employee) {  
        EmployeeModel empmodel = new EmployeeModel();  
        empmodel.Id = employee.Id;  
        empmodel.Name = employee.Name;  
        empmodel.Designation = employee.Designation;  
        empmodel.Address = new Address() {  
            City = employee.City, State = employee.State  
        };  
        return empmodel;  
    }  


To overcome this situation, we have a library called AutoMapper.
Incorporate this library into your application by following the below steps.
Open Visual Studio and Click on File - New Project and select ASP.NET CORE WEB APPLICATION,


Click on Ok and you’ll get the below window where you have to select WebApp (MVC).


As soon as you click on the Ok button your application is ready.

Now, the actual auto mapper should take place. For that, we need to add NuGet reference to the solution. Make sure we have to add two references to solution
    Add Main AutoMapper Package to the solution,

Now, add the Auto mapper dependency Injection Package,

Now, call AddAutoMapper from StartUp.cs file as shown below,
public void ConfigureServices(IServiceCollection services) {  
            services.AddMvc();  
            services.AddAutoMapper();  
        }  


Now, create the MappingProfile.cs file under the root project and write the below snippet
 public class MappingProfile: Profile {  
            public MappingProfile() {  
                CreateMap < Employee, EmployeeModel > ()  
            }  
        }  


Here CreateMap method is used to map data between Employee and EmployeeModel.

If you observe here we called ForMember method, which is used when we have different datatypes in source and destination classes.

Employee Class should be like this,
    namespace ASPNETCORE_AUTOMAPPER.Models {  
        public class Employee {  
            public int Id {  
                get;  
                set;  
            }  
            public string Name {  
                get;  
                set;  
            }  
            public string Designation {  
                get;  
                set;  
            }  
            public string City {  
                get;  
                set;  
            }  
            public string State {  
                get;  
                set;  
            }  
        }  
    }  


EmployeeModel.cs should be like this,
    namespace ASPNETCORE_AUTOMAPPER.Models {  
        public class EmployeeModel {  
            public int Id {  
                get;  
                set;  
            }  
            public string Name {  
                get;  
                set;  
            }  
            public string Designation {  
                get;  
                set;  
            }  
            public Address Address {  
                get;  
                set;  
            }  
        }  
        public class Address {  
            public string City {  
                get;  
                set;  
            }  
            public string State {  
                get;  
                set;  
            }  
        }  
    }
 

In Employee.cs file having City and State properties but in EmployeeModel.cs we have Address type. So if we try to map these two models we may end up missing type configuration error. So to overcome that issue we have to use ForMember method which tells mapper what properties it should map for that particular Address field. So we have to tweak the MappingProfile.cs file like below:
    public class MappingProfile: Profile {  
        public MappingProfile() {  
            CreateMap < Employee, EmployeeModel > ().ForMember(dest => dest.Address, opts => opts.MapFrom(src => new Address {  
                City = src.City, State = src.State  
            }));  
        }  
    }  

So the next step is we have to hook this up from our controller;  just follow the below snippet
    namespace ASPNETCORE_AUTOMAPPER.Controllers {  
        public class EmployeeController: Controller {  
            private readonly IMapper _mapper;  
            public EmployeeController(IMapper mapper) {  
                _mapper = mapper;  
            }  
            public IActionResult Index() {  
                    return View();  
                }  
                [HttpPost]  
            public EmployeeModel Post([FromBody] Employee employee) {  
                EmployeeModel empmodel = new EmployeeModel();  
                empmodel = _mapper.Map < Employee, EmployeeModel > (employee);  
                return empmodel;  
            }  
        }  
    }
 

Here we have injected IMapper to EmployeeController and performed mapping operation between Employee and EmployeeModel

If you pass data to Employee object,  it will directly map to EmployeeModel object with the help of Mapper.

Now if you observe, EmployeeModel is filled in with all the property data with the help of Mapper. This is the actual beauty of AutoMapper.

So if you come across a requirement to map data from your DTOs to Domain object choose Automapper and it will do all your work with less code.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: URL Creation Fundamentals In MVC

clock November 8, 2021 06:49 by author Peter

In this article, we are going to explore different ways of URL creation in MVC and different fundamental concepts of MVC. So let's get started with MVC fundamentals. We have two different approaches available while creating an URL in MVC framework.
    ActionLink
    Raw HTML

Action LInk in the background queries the routing engine whenever the URL associated with the given controllers ACTION. Sometimes we do have Custom URLs associated with an action, and we require to change that URL in future. For this scenario actionLink will pick up the latest URL, you don't need to make any changes.

On the other hand, if you are using raw HTML, you need to update your links when URLs changed.

As a good programmer, we should always avoid changing URLs as URLs are the public contract of your app and can be referenced by other apps, and many times users bookmark the URLs. If you change them, all these bookmarks and references will be broken.

In the end, the decision is up to the programmer's choice, no hard and fast rule here.

Again, the simplest way is using raw HTML

1: Raw HTML
Example,
<a href = "Courses/Index"> View Course</a>

2: ActionLink
Below is the example of using ActionLink for URL creation.
@HTML.ActionLink("View Courses","Index","Courses")

If the targeted action needs a parameter we can make use of an anonymous object to pass the parameter values.
@HTML.ActionLink("View Courses","Index","Courses", new {id = 1})

This will generate a link as - courses/index/1

This method doesn't generate the link for a reason, we need to pass another argument to ActionLink. This argument can be null or an anonymous object to render any additional HTML attribute.
@HTML.ActionLink("View Courses","Index","Courses", new {id = 1}, null)

We have different HTML helpers available in MVC 

Type Helper Method
ViewResult View()
PartialViewResult PartialView()
RedirectResult Redirect()
ContentResult Content()
JsonResult Json()
RedirectToRouteResult RedirectToAction()
FileResult File()
HttpNotFoundResult HttpNotFound()
EmptyResult  

Passing Data to views in MVC
We should avoid passing data using ViewData and ViewBag as these methods are fragile and need a lot of casting which makes code ugly. Instead, we can pass model or viewModel directly to view.
return View(Course);

Razor Views
@if(condition)
{
    // c# or HTML code
}


@foreach(...)
{
}


We can render a class or any attribute conditionally as follows,
@{
    var className=Model.Movies.Count >3 ? "Popular" : null;
}
<h2 class = "@className">...</h2>

Partial View

@Html.Partial("_NavBar")

Types of Routing in MVC
1: Convention based Routing

Here we can specify the routing in RouteConfig.cs file and mention the Controller, action which needs to be invoked using mapRoute method of routes collection.

2: Attribute based Routing

Here we can apply route by decorating the action method with the Route keyword followed by the path.

Authentication in MVC
Use [authorize] keyword. Apply it to action, controller or globally (in FilterConfig.cs)
Enabling Social Login in MVC

Step 1
Enable SSL: Select project, press F4, set SSL enabled to true.

Step 2
Copy SSL URL, select the project, go to properties, in the Web tab, set startup URL.

Step 3
Apply RequireSSL filter globally in FilterConfig.cs file.

Step 4
Register your app with external authentication providers to get secret key/secret. In AppStart.cs/Startup.Auth.cs, add corresponding providers and your key/secret.
Summary

In this article, we explored different ways of URL creation in MVC and different fundamental concepts of MVC. I hope you liked the article. Until Next Time - Happy Learning Cheers



ASP.NET MVC Hosting - HostForLIFEASP.NET :: State Management In ASP.NET MVC

clock October 29, 2021 09:15 by author Peter

As we all know, HTTP is a stateless protocol, i.e., each HTTP request does not know about the previous request. If you are redirecting from one page to another page, then you have to maintain or persist your data so that you can access it further. To do this, there were many techniques available in ASP.NET like ViewState, SessionState,

ApplicationState etc.
ASP.NET MVC also provides state management techniques that can help us to maintain the data when redirecting from one page to other page or in the same page after reloading. There are several ways to do this in ASP.NET MVC -
    Hidden Field
    Cookies
    Query String
    ViewData
    ViewBag
    TempData

The above objects help us to persist our data on the same page or when moving from “Controller” to “View” or “Controller” to Controller”. Let us start practical implementation of these so that we can understand in a better way.

Hidden Field
It is not new, we all know it from HTML programming. Hidden field is used to hide your data on client side. It is not directly visible to the user on UI but we can see the value in the page source. So, this is not recommended if you want to store a sensitive data. It’s only used to store a small amount of data which is frequently changed.

The following code is storing the Id of employee and its value is 1001.
    @Html.HiddenFor(x=>x.Id)  

If you open the page source code for that page in the browser, you will find the following line of code, which is nothing but the HTML version of the above code with value. Just focus on last three attributes.

    <input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="1001" />  

Cookies
Cookies are used for storing the data but that data should be small. It is like a small text file where we can store our data. The good thing is that a cookie is created on client side memory in the browser. Most of the times, we use a cookie for storing the user information after login with some expiry time. Basically, a cookie is created by the server and sent to the browser in response. The browser saves it in client-side memory.

We can also use cookies in ASP.NET MVC for maintaining the data on request and respond. It can be like the below code.
    HttpCookie cookie = new HttpCookie("TestCookie");  
    cookie.Value = "This is test cookie";  
    this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);  


Here, we have created one cookie and named it as “TestCookie”. We can create multiple cookies and add with Response. For getting the value from an existing cookie, we first need to check that the cookie is available or not; then, we can access the value of the cookie.
    if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("TestCookie"))  
    {  
        HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["TestCookie"];  
      
        ViewBag.CookieMessage = cookie.Value;  
    }  

Cookies are all depended on expiry, you can create a cookie on one action method in a controller and it will save on the client side and can be accessed in another action method easily.

Query String
In ASP.NET, we generally use a query string to pass the value from one page to the next page. Same we can do in ASP.NET MVC as well.
http://localhost:49985/home/editemployee?name=TestValue

I am making one request with the above URL. You can see that in this, I am passing name’s value as a query string and that will be accessible on “EditEmployee” action method in “Home” controller as the following image shows.

ViewData
It helps us to maintain your data when sending the data from Controller to View. It is a dictionary object and derived from ViewDataDictionary. As it is a dictionary object, it takes the data in a key-value pair.

Once you create ViewData object, pass the value, and make redirection; the value will become null. The data of ViewData is not valid for next subsequent request. Take care of two things when using ViewData, first, check for null and second, check for typecasting for complex data types.
    public ActionResult Index()  
    {  
        Employee emp = new Employee()  
        {  
            Id = 1001,  
            Name = "Peter",  
            Address = "London",  
            Age = 25  
        };  
                  
        ViewData["Message"] = "This is ViewData";  
        ViewData["Emp"] = emp;  
      
        return View();  
    }  


The above code contains two ViewData dictionary objects - ViewData["Message"] and ViewData["Emp"]. The first one is a simple string value but the next one contains complex employee data. When the View is going to render, we need to first check the ViewData for null and if it is not, then we can get the value.
    @{  
        ViewBag.Title = "Home Page";  
    }  
      
    <div class="row">  
        <div class="col-md-4">  
            <h2>Employee Details</h2>  
            <br />  
            <p>  
                @if(ViewData["Message"] !=null)  
                {  
                    <b>@ViewData["Message"].ToString();</b>  
                }  
            </p>  
            <br />  
            @if (ViewData["Emp"] != null)  
            {  
      
                var emp = (MVCStateManagement.Models.Employee)ViewData["Emp"];  
                <table>  
                    <tr>  
                        <td>  
                            Name :  
                        </td>  
                        <td>  
                            @emp.Name  
                        </td>  
                    </tr>  
                    <tr>  
                        <td>  
                            Address :  
                        </td>  
                        <td>  
                            @emp.Address  
                        </td>  
                    </tr>  
                    <tr>  
                        <td>  
                            Age :  
                        </td>  
                        <td>  
                            @emp.Age  
                        </td>  
                    </tr>  
                </table>              
            }  
        </div>  
    </div>  

Note
    If you are using ViewData that is not defined on Controller, then it will throw an error; but with ViewBag, it will not.
    Do not use ViewBag and ViewData with the same name, otherwise, only one message will display. See the following code in the controller is using both ViewData and ViewBag with same name “Message”.
    public ActionResult Index()  
    {  
        ViewData["Message"] = "This is ViewData";  
        ViewBag.Message = "This is ViewBag";              
      
        return View();  
    }  

On view defined both as following.  
    <b>@ViewBag.Message</b>    
    @if(ViewData["Message"]!=null)    
    {    
        ViewData["Message"].ToString();    
    }  


The output will show only one message and that will be the last one [in this case, message will be “This is ViewBag”].

TempData
TempData is also a dictionary object as ViewData and stores value in key/value pair. It is derived from TempDataDictionary. It is mainly used to transfer the data from one request to another request or we can say subsequent request. If the data for TempData has been read, then it will get cleaned. To persist the data, there are different ways. It all depends on how you read the data.

No Read Data
If you haven’t read the data in redirection process, then your data is available with the next subsequent request. You can see that in the following code, we have set up a TempData[“Emp” but neither read it in any action method nor in view.

So, once the “About” page renders and if we move to “Contact” page, the TempData[“Emp”] will be available.

Note
Do not read data on View.
    public ActionResult Index()  
    {  
        Employee emp = new Employee() { Id = 1001, Name = "Peter", Address = "London", Age = 25 };  
      
        //Setting the TempData  
        TempData["Emp"] = emp;  
        return RedirectToAction("Index1");  
    }  
    public ActionResult Index1()  
    {  
        //Not reading TempData  
        return RedirectToAction("Index2");  
    }  
    public ActionResult Index2()  
    {  
        //Not reading TempData  
        return RedirectToAction("About");  
    }  
    public ActionResult About()  
    {  
        //Not reading TempData  
        return View();  
    }    
           
    public ActionResult Contact()  
    {  
        //Data will available here because we have not read data yet  
        var tempEmpData = TempData["Emp"];  
        return View();  
     }  


Normal Data Read
If you read the data on “About” page when it will render and try to access the value on “Contact” page, it will not be available.
    @{  
        ViewBag.Title = "About";  
    }  
    <h2>About Page</h2>  
    <br />  
    @{   
        var data = (MVCStateManagement.Models.Employee)TempData["Emp"];  
    }  

TempData will not be available with Contact page because we have already read that data on “About” page. TempData is only available with subsequent request if you have not read yet.
    public ActionResult Contact()  
    {  
        //Data will not available here because already read on About page  
        var tempEmpData = TempData["Emp"];  
        return View();  
     }  


Keep TempData
If you still want to persist your data with the next request after reading it on “About” page that you can use “Keep()” method after reading data on “About” page. The Keep method will persist your data for next subsequent request.
    @{   
        var data = (MVCStateManagement.Models.Employee)TempData["Emp"];  
        TempData.Keep();  
    }  
    public ActionResult Contact()  
    {  
        //TempData will available here because we have keep on about page  
        var tempEmpData = TempData["Emp"];  
        return View();  
     }  


Peek TempData
Using Peek() method, we can directly access the TempData value and keep it for next subsequent request.
    @{   
        var data = (MVCStateManagement.Models.Employee)TempData.Peek("Emp");      
    }  

When we move to “Contact” page, the TempData will be available.
    public ActionResult Contact()  
    {  
        //TempData will available because we have already keep data using Peek() method.  
        var tempEmpData = TempData["Emp"];  
        return View();  
     }  


I hope this post helps you. Please share your feedback which will help me improve the next posts. If you have any doubts, please ask in the comments section.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Validation Message and Validation Summary Tag Helper in ASP.NET MVC Core 3.1

clock October 4, 2021 07:26 by author Peter

This blog will explain validation messages and the validation summary tag helper in ASP.NET MVC core. Validation messages and the validation tag helper are similar to ValidationMessage and ValidationMessageFor in asp.net MVC.


ValidationMessage TagHelper: validation message tag helper targets span element with asp-validation-for attribute which display validation message from modal class validation property.

Validation Summary TagHelper: Validation Summary tag helper target the div element. It has asp-validation-sammary attribute which display model validation summary on browser client.

ValidationMessage: It is an extension method that is a loosely typed method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object.

ValidationMessageFor: This method will only display an error if you have configured Data Annotations attribute to the specified property in the model class.

ValidationSummary: This ValidationSummary helper method generates an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.
Steps:
Step 1: Create asp.net MVC core project in visual studio 2019 with MVC (Model-View-Controller) template.
Step 2: Right-click on models folder and “Add” class with name student.
using System;  
using System.ComponentModel.DataAnnotations;  
 
namespace ValidationMessageValidationSummaryTagHelper_Demo.Models  
{  
    public class Student  
    {  
        [Key]  
        public int Id { get; set; }  
 
        [Required(ErrorMessage = "Please enter name")]  
        public string Name { get; set; }  
 
        [Required(ErrorMessage = "Please choose gender")]  
        public string Gender { get; set; }  
 
        [Required(ErrorMessage = "Please choose date of birth")]  
        [Display(Name = "Date of Birth")]  
        [DataType(DataType.Date)]  
        public DateTime DateofBirth { get; set; }  
 
        [Required(ErrorMessage = "Please enter address")]  
        [StringLength(255)]  
        public string Address { get; set; }  
    }  
}  


Step 3: Open HomeController or add HomeController if you don’t have it. Add the action method Create in controller class.
using System;  
using System.Collections.Generic;  
using System.Diagnostics;  
using System.Linq;  
using System.Threading.Tasks;  
using Microsoft.AspNetCore.Mvc;  
using Microsoft.Extensions.Logging;  
using ValidationMessageValidationSummaryTagHelper_Demo.Models;  
 
namespace ValidationMessageValidationSummaryTagHelper_Demo.Controllers  
{  
    public class HomeController : Controller  
    {  
        public IActionResult Index()  
        {  
            return View();  
        }  
 
        public IActionResult Create()  
        {  
            return View();  
        }  
 
        [HttpPost]  
        public IActionResult Create(Student student)  
        {  
            if (ModelState.IsValid)  
            {  
 
            }  
            return View();  
        }  
    }  
}  

Step 4 Right click on create action method and “Add” create view and write following code.
@model ValidationMessageValidationSummaryTagHelper_Demo.Models.Student  
@{  
    ViewData["Title"] = "Create";  
}  
 
<div class="card">  
    <div class="card-header">  
        <h4>Student Details</h4>  
    </div>  
    <div class="card-body">  
        <div asp-validation-summary="All"></div>  
        <form asp-action="Create">  
            <div class="form-group">  
                <label asp-for="Name" class="label-control"></label>  
                <input asp-for="Name" class="form-control" />  
                <span asp-validation-for="Name" class="text-danger"></span>  
            </div>  
            <div class="form-group">  
                <label asp-for="Gender" class="label-control"></label>  
                <select asp-for="Gender" class="custom-select">  
                    <option value="">Choose Geneder</option>  
                    <option value="Male">Male</option>  
                    <option value="Female">Female</option>  
                </select>  
                <span asp-validation-for="Gender" class="text-danger"></span>  
            </div>  
            <div class="form-group">  
                <label asp-for="DateofBirth" class="label-control"></label>  
                <input asp-for="DateofBirth" class="form-control" />  
                <span asp-validation-for="DateofBirth" class="text-danger"></span>  
            </div>  
            <div class="form-group">  
                <label asp-for="Address" class="label-control"></label>  
                <textarea asp-for="Address" class="form-control"></textarea>  
                <span asp-validation-for="Address" class="text-danger"></span>  
            </div>  
            <div>  
                <button type="submit" class="btn btn-sm btn-primary rounded-0">Submit</button>  
            </div>  
        </form>  
    </div>  
</div>  

The Validation Summary Tag Helper is used to display a summary of validation messages. The asp-validation-summary attribute value can be any of the following:

asp-validation-summary

Validation messages displayed

ValidationSummary.All

Property and model level

ValidationSummary.ModelOnly

Model

ValidationSummary.None

None

    <div asp-validation-summary="All"></div>  
    <div asp-validation-summary="ModelOnly"></div>  
    <div asp-validation-summary="None"></div>  


Step 5: Add the following CSS in site.css file under wwwroot folder.

    .field-validation-error {  
        color: #e80c4d;  
        font-weight: bold;  
    }  
    .field-validation-valid {  
        display: none;  
    }  
    input.input-validation-error {  
        border: 1px solid #e80c4d;  
    }  
    .validation-summary-errors {  
        color: #e80c4d;  
        font-weight: bold;  
        font-size: 1.1em;  
    }  
    .validation-summary-valid {  
        display: none;  
    } 

Step 6: Build and run your application Ctrl+F5




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Routing In MVC Application ( Types And Implementation Methods )

clock September 22, 2021 07:47 by author Peter

Introduction
This article will summarize adjusting routing configurations in an MVC project
The aim of the adjustments was to trace a problem that a certain action was hit multiple times
The problem had nothing to do with routing, but I investigated routing configuration in my search for the cause

The rest of the article will describe different types of routing supported and the configurations needed in the levels of,

  • Application execution pipeline (middleware)
  • The controllers and action

Definitions
Routing is responsible for matching incoming HTTP requests and dispatching those requests to the app's executable endpoints
Endpoints are the app's units of executable request-handling code. Endpoints are defined in the app and configured when the app starts

Types of routing
Conventional Based Routing

It is the basic routing type implemented by default.
You will find the middleware pipeline configured to implement this type through the following code in the startup.cs.
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
})


The HTTP request with a URL of format /Home/Index or Home/Index/1 will be processed by the action method Index n Home Controller or By Z Action method in the Y controller if the URL was http://abc.com/Y/Z.

Area Conventional Based Routing

  • Areas provide a way to partition an ASP.NET Core Web app into smaller functional groups
  • Each group has its own set of Razor Pages, controllers, views, and models

Controller level

View Level


Application execution pipeline can be configured to enable area-based routing in either one of the following two ways.
Using a code similar to the previous one as follows,
endpoints.MapControllerRoute(name: "Area", pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}", defaults: new {
    area = "Home"
});


Using MapAreaControllerRoute method IEndpointRouteBuilderInterface as in the following example,

endpoints.MapAreaControllerRoute(pattern: "{area}/{controller}/{action}/{id?}", name: "areas", areaName: "Home", defaults: new {
    controller = "Home", action = "Index"
});

Mixed Conventional Based Routing
    In Mixed Conventional Based Routing
    The URL specified in the HTTP request is checked against the patterns specified in both routing types
    Default routing is determined by finding a match against the patterns specified in each routing type in order

Attribute routing
Hopefully, we will discuss this in a later article.

Examples
Default routing type (conventional without area support).
configuration in the startup.cs
app.UseEndpoints(endpoints => {
    endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
})

Result

Conventional with area support
Configuration in the startup.cs either,
endpoints.MapAreaControllerRoute(pattern: "{area}/{controller}/{action}/{id?}", name: "areas", areaName: "Home", defaults: new {
    controller = "Home", action = "Index"
});


or,
endpoints.MapControllerRoute(name: "Area", pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}", defaults: new {
    area = "Home"
});

Result

Mixed conventional

Example 1 - configuration

endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapAreaControllerRoute(pattern: "{area}/{controller}/{action}/{id?}", name: "areas", areaName: "Home", defaults: new {
    controller = "Home", action = "Index"
});

Result

Example 2 - Configuration
endpoints.MapAreaControllerRoute(pattern: "{area}/{controller}/{action}/{id?}", name: "areas", areaName: "Home", defaults: new {
    controller = "Home", action = "Index"
});
endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");

Result

Redirecting from an action in a controller not belonging to an area to an action belonging to an area.

From Controller this will work only if area conventional routing comes first in the startup.cs file as follows,
endpoints.MapAreaControllerRoute(pattern: "{area}/{controller}/{action}/{id?}", name: "areas", areaName: "Home", defaults: new {
    controller = "Home", action = "Index"
});
endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");

Otherwise, errors of too many directions will occur.


Through a hyperlink.

Example


Result

This article summarized different conventional routing implementation methods as well as ways to navigate between routes.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Simple Blazor Components In .NET CORE MVC 3.1

clock September 16, 2021 10:05 by author Peter

In this article, we will add a Razor component to our existing .NET Core MVC project.
 
Blazor is a framework for building interactive client-side web UI with .NET. With it, you can:

    Create rich interactive UIs using C# instead of JavaScript.
    Share server-side and client-side app logic written in .NET.
    Render the UI as HTML and CSS for wide browser support, including mobile browsers.

Blazor apps are based on components. A component in Blazor is an element of UI, such as a page, dialog, or data entry form.
 
Let's start with a few simple steps.

Step 1

Step 2


Step 3
Add a Microsoft.AspNetCore.Components reference to your project if not available.

Step 4
Add a Component folder inside the view/shared folder, then add a Razor component.


Step 5
For the Razor component we have written a simple method named "GetData", which you can see below. Also, I have made 2 public properties for getting data from the view and decorating it with the attribute name as Parameter.

    <div class="card-header">  
      
        <h3>DataComponent</h3>  
        <button @onclick="Getdata" class="btn btn-dark">Click to GetData    </button>  
    </div>  
    <div class="card-body">  
        <br />  
        <div class="@style">@Data </div>  
    </div>  
      
    @code {  
        [Parameter]  
        public string Data { get; set; } = string.Empty;  
        [Parameter]  
        public string style { get; set; }  
        private void Getdata()  
        {  
            Data = "I am Working";  
            style = "badge-success";  
      
        }  
      
    }  


Step 6
The below code you need to add to your _Layout.cshtml  
This is for registering Blazor to your web application:
    <base href="~/" />  
    <script src="_framework/blazor.server.js"></script>


Step 7
Add simple _Imports.razor file to your root of the project which consists of the below code. These namespaces are required to access the component features over your components.

    @using System.Net.Http  
    @using Microsoft.AspNetCore.Authorization  
    @using Microsoft.AspNetCore.Components.Authorization  
    @using Microsoft.AspNetCore.Components.Forms  
    @using Microsoft.AspNetCore.Components.Routing  
    @using Microsoft.AspNetCore.Components.Web  
    @using Microsoft.JSInterop  
      
    @using System.IO   

Step 8
Add services.AddServerSideBlazor(); to your startup file method name ConfigureServices.
Add endpoints.MapBlazorHub(); to your Configure method.

    public void ConfigureServices(IServiceCollection services)  
        {   
            services.AddServerSideBlazor();  
            services.AddControllersWithViews();  
        }  
      
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
        {  
            if (env.IsDevelopment())  
            {  
                app.UseDeveloperExceptionPage();  
            }  
            else  
            {  
                app.UseExceptionHandler("/Home/Error");  
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
                app.UseHsts();  
            }  
            app.UseHttpsRedirection();  
            app.UseStaticFiles();  
      
            app.UseRouting();  
      
            app.UseAuthorization();  
      
            app.UseEndpoints(endpoints =>  
            {  
                endpoints.MapControllerRoute(  
                    name: "default",  
                    pattern: "{controller=Home}/{action=Index}/{id?}");   
                endpoints.MapBlazorHub();  
            });  
      
        }  

Step 9
The last step is to render components on your View page.
You can see that I am passing 2 parameters as requested in our DataViewComponent.razor file

    @{  
        ViewData["Title"] = "Home Page";  
    }  
    <div class="text-center">  
        <h1 class="display-4">Welcome</h1>  
          
    </div>  
      
    <div class="card">  
         
            @(await Html.RenderComponentAsync<BlazorComponentProject.Views.Shared.Components.DataViewComponent>(RenderMode.ServerPrerendered,new {  Data="I came from Index",style= "badge-danger" }))  
               
          
    </div>   

Our main focus in this article was to help you to integrate your existing Web application build in .NET Core MVC 3.1 with Blazor and use the Blazor components in it. Please refer to the project and debug the process for more understanding. I hope it helps!


ASP.NET MVC Hosting - HostForLIFEASP.NET :: Scheduling In ASP.NET MVC Core

clock September 6, 2021 07:22 by author Peter

In this blog, we will learn how to use the Quartz scheduler in ASP.NET Core. We may perform jobs in the background using this scheduler. We can use Quartz scheduling to perform a job every 5 minutes.


Step 1
To begin, make a project with the ASP.NET core web application template. Choose Asp.net MVC for your online application.

Step 2
There are two ways to install the Quartz package.

Search for Quartz in the Nuget package manager and install it.

Using NuGet package manager console.


Step 3
Now we'll make a folder under the models and call it anything we want. We'll make a task and a scheduler in this folder.

Create Task
The objective is to create a basic class where you can write your logic.

We'll add a task in the schedule folder and call it task1. We shall save the current time in a text file in this task.

The class code is shown below,
using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace QuartzSchduling.Models.Schedule {
    public class Task1: IJob {
        public Task Execute(IJobExecutionContext context) {
            var task = Task.Run(() => logfile(DateTime.Now));;
            return task;
        }
        public void logfile(DateTime time) {
            string path = "C:\\log\\sample.txt";
            using(StreamWriter writer = new StreamWriter(path, true)) {
                writer.WriteLine(time);
                writer.Close();
            }
        }
    }
}

Now, beneath the c drive, make a folder and call it to log. In this folder, we'll make a text file with the name sample.txt.

Scheduler task
We'll now construct a new class that will handle the trigger task. This class's job is to start the task that I've already established. Set the frequency at which it runs.

Below is the code of the class,
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace QuartzSchduling.Models.Schedule {
    public class SchedulerTask {
        private static readonly string ScheduleCronExpression = "* * * ? * *";
        public static async System.Threading.Tasks.Task StartAsync() {
            try {
                var scheduler = await StdSchedulerFactory.GetDefaultScheduler();
                if (!scheduler.IsStarted) {
                    await scheduler.Start();
                }
                var job1 = JobBuilder.Create < Task1 > ().WithIdentity("ExecuteTaskServiceCallJob1", "group1").Build();
                var trigger1 = TriggerBuilder.Create().WithIdentity("ExecuteTaskServiceCallTrigger1", "group1").WithCronSchedule(ScheduleCronExpression).Build();
                await scheduler.ScheduleJob(job1, trigger1);
            } catch (Exception ex) {}
        }
    }
}

You've only completed one job in the code above. If you wish to execute more than one job, just create a new class, as we did with task1.

We will now add this job to taskscheduler.
//First Task
var job1 = JobBuilder.Create < Task1 > ().WithIdentity("ExecuteTaskServiceCallJob1", "group1").Build();
var trigger1 = TriggerBuilder.Create().WithIdentity("ExecuteTaskServiceCallTrigger1", "group1").WithCronSchedule(ScheduleCronExpression).Build();
//  Second Task
var job2 = JobBuilder.Create < Task2 > ().WithIdentity("ExecuteTaskServiceCallJob2", "group2").Build();
var trigger2 = TriggerBuilder.Create().WithIdentity("ExecuteTaskServiceCallTrigger2", "group2").WithCronSchedule(ScheduleCronExpression).Build();
await scheduler.ScheduleJob(job1, trigger1);
await scheduler.ScheduleJob(job2, trigger2);

You've just seen the ScheduleCronExpression in the code above. The cron expression is a format that specifies how often your task will be performed.

Below I give you some examples,

Every Second : * * * ? * *
Every Minute : 0 * * ? * *
Every Day noon 12 pm : 0 0 12 * * ?

Final Step
Now register your scheduler task to startup.

public Startup(IConfiguration configuration) {
    //The Schedular Class
    SchedulerTask.StartAsync().GetAwaiter().GetResult();
    Configuration = configuration;
}


All you have to do now is run your code and check your text file, which is often running at the time you set in the cron expression.

In this blog, we learned how to schedule a task in asp.net core, which we can use to perform any operation, such as sending mail at a certain time. As a result, we can perform any operation with this, and it's quite easy to set up.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: ASP.NET MVC Model Binder And Custom Binder

clock September 1, 2021 08:26 by author Peter

ASP.NET MVC Model binding is one of the best features in ASP.NET MVC Framework. It is a bridge between HTTP request and action methods. It helps GET and POST to get automatically transferred into the data model.

MVC Model Binder uses Default Model Binder for building model parameter for MVC runtime.

Now,  before this we would like to first explain simple model binding.

Now, we have created a new MVC Web application project by File- New Project- Web Application – MVC.
Now, we will add a new strongly typed View which we will bind to the model, as shown below.
    @model ModelBinding.Models.Client  
    @ {  
        ViewBag.Title = "GetClient";  
    } < h3 Details < /h3>   
      < h2 >   
      Cleint Code: @Model.ClientCode   
        < br / >   
        Cleint Name: @Model.ClientName   
    < /h2> 

Now, add a Client Model in Models folder, as shown below.
    public class Client {  
        public string ClientCode {  
            get;  
            set;  
        }  
        public string ClientName {  
            get;  
            set;  
        }  
    } 

Add ClientController which is shown below.
    public class ClientController: Controller {  
        // GET: Client  
        public ActionResult GetClient() {  
            Client cnt = new Client {  
                ClientCode = "1001",  
                    ClientName = "Peter"  
            };  
            return View(cnt);  
        }  
    }  


Now, add another action method as EnterClient which will allow the users to enter client details, as shown below.
    public ActionResult EnterCleint() {  
        return View();  
    }  


As shown below, it is having two textboxes and Submit button. Along with it, the form is using POST method for the action Submit.
    @ {  
        ViewBag.Title = "EnterCleint";  
    } < h2 > EnterCleint < /h2> < form action = "Submit"  
    method = "post" > Cleint Code: < input type = "text"  
    name = "ClientCode " / > < br / > Cleint Name: < input type = "text"  
    name = "ClientName " / > < br / > < input type = "submit"  
    value = "Submit"  
    id = "Submit" / > < /form>  
 Now, we will create Submit action methond in the Controller.
    public ActionResult Submit() {  
        Client cnt = new Client {  
            ClientCode = Request.Form["CleintCode"],  
                ClientName = Request.Form["CleintName"]  
        };  
        return View("GetClient", cnt);  
    }  


In the above code, we are fetching the values on the basis of textbox name and assigning it to Client and passing to GetCleint View.

Now, you can improve your code by adding parameter of type model in action method as shown below,
    public ActionResult Submit(Client cnt) {  
        return View("GetClient", cnt);  
    }  


Here, we have to take care textboxes name must be same in above example.

Now, if we will take a real-life example - the designing team works on design and developers work on development i.e. property name of the model and control names are different. In this case, it is very difficult to maintain the name on both sides or we can say lots of efforts is required for the same.

To overcome such a scenario, we can take the help of Model Binders, we can say Model Binder has mapping code which connects your user interface with your Model. It acts like a bridge between the Model and View.

Now, let’s see the same with example.

Lets add a View having two textboxes and Submit button. Along with it, the form is using post method to action Submit.
    @ {  
        ViewBag.Title = "EnterCleint";  
    } < h2 > EnterCleint < /h2> < form action = "Submit"  
    method = "post" > Cleint Code: < input type = "text"  
    name = "txtClientCode" / > < br / > Cleint Name: < input type = "text"  
    name = "txtClientName" / > < br / > < input type = "submit"  
    value = "Submit"  
    id = "Submit" / > < /form>  


In the above example, the View is having two textboxes, i.e., txtClientCode and txtClientName which are not same as property names of Client model.

Now, add a new folder as Utilities.
Now, add a class, ClientBinder class, which will implement the System.Web.Mvc.IModelBinder as shown below.
    public class ClientBinder: IModelBinder {  
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {  
            HttpContextBase context = controllerContext.HttpContext;  
            string clientCode = context.Request.Form["txtClientCode"];  
            string clientName = context.Request.Form["txtClientName"];  
            return new Client {  
                ClientCode = clientCode,  
                    ClientName = clientName  
            };  
        }  
    }  

In the above code, we are accessing the form object from the request object with the help of context object and converting it into Model, i.e., Client.

Now, we need to use the above ClientBinder and map it to our Client object which we will do in below.
    ActionResult Submit([ModelBinder(typeof(ClientBinder))] Client cnt)  

In the above code, we are using ClientBinder.

Now, add/modify the action method.
    public ActionResult Submit([ModelBinder(typeof(ClientBinder))] Client cnt) {  
        return View("GetClient", cnt);  
    }  


That's it. We are done here.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in