European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Model Binders for ASP.NET MVC with Examples

clock September 15, 2023 06:57 by author Peter

ASP.NET MVC (Model-View-Controller) is a popular web development framework for creating strong and maintainable web applications. Model Binders are an important part of it. Model Binders play a critical role in mapping incoming HTTP requests to action method parameters, making it easier to work with client-side data. In this blog post, we will delve into the world of ASP.NET MVC Model Binders and present practical examples of how to use them.

What Exactly Are Model Binders?
Model Binders are ASP.NET MVC components that are responsible for mapping data from numerous sources, such as form fields, query strings, route parameters, and JSON payloads, to action method parameters. They are critical in easing the process of taking user input and transforming it into highly typed objects that your program may use.

Here's a detailed breakdown of how Model Binders work:

  • A user delivers an HTTP request to your ASP.NET MVC application, generally via a form submission or an API call.
  • Routing: The MVC framework uses routing rules to identify which controller and action method should handle the request.
  • Model Binders are useful in this situation. They collect data from the HTTP request and transfer it to the action method's arguments. The mapping is based on the names and types of parameters.
  • Execution of Action Methods: After the data is bound to the action method parameters, the method is executed using the provided data.
  • The action method processes the data and provides a response, which is returned to the client.

Now, let's look at some real-world examples of Model Binders.

Binding to Simple Types as an Example
Assume you have a simple HTML form with a single text input field named "username." You wish to capture the user's entered username.
public ActionResult Register(string username)
{
    // Process the username
    return View();
}

In this scenario, the Model Binder automatically binds the username parameter based on the name of the form input field.

Example 2: Complex Type Binding
Model Binders can also be used to tie complex types, such as custom classes, to action method parameters. Consider the following User class:

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}


You can bind an instance of the User class from a form submission as follows:
public ActionResult CreateUser(User user)
{
    // Process the user object
    return View();
}

The Model Binder will automatically populate the User object's properties using the submitted form data.
Example 3. Custom Model Binders

In some cases, you might need to implement custom Model Binders to handle complex scenarios. For example, if you want to bind data from a non-standard source or perform custom data transformation, you can create a custom Model Binder.
public class CustomBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // Custom logic to bind the model
        // Example: Read data from a cookie and populate the model
    }
}


To use the custom Model Binder, you can decorate your action method parameter with the [ModelBinder] attribute:

public ActionResult MyAction([ModelBinder(typeof(CustomBinder))] MyModel model)
{
    // Custom binding logic applied
    return View();
}

ASP.NET MVC Model Binders are critical components that let you manage user input data in your online applications. They make it simple to convert HTTP request data to action method parameters, making it easier to work with user-supplied data. Model Binders provide a strong technique for streamlining data binding in your ASP.NET MVC applications, whether you're dealing with simple types or complex objects.

You can design more efficient and maintainable web apps with ASP.NET MVC if you understand how Model Binders function and use them effectively.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Using Elastic Search With ASP.NET MVC

clock September 8, 2023 09:06 by author Peter

In this article, we are going to learn how to use elastic search with ASP.NET MVC in step by step way.We are already in the fifth part of this article. Till now, we have covered a lot in elastic search starting from how to configure elastic search to how to insert data into elastic search, further using Kibana for visualizing data, and at last, we have learned about Logstash and how to insert a bulk of data from MSSQL and MYSQL into elastic search. Now, it’s time to learn how we can query elastic search documents from ASP.NET MVC because at last, we need to show data to end-users in a fast way as possible.

 

If you are a beginner and you do not have an idea what is elastic search but you want to know it, then the below links will help you to kick start with elastic search.

Create ASP.NET MVC Application
Let’s create a simple ASP.NET MVC application with the name “WebElasticSearch”.

After entering the name, it will show another window for project selection. There, just choose “MVC” Template and change Authentication to “No Authentication” and click OK to create the project.

Project Structure

Next, we are going to install NuGet packages.            

Installing NuGet Packages

We are going to install 2 NuGet packages.

    Net
    Nest

After installing the NuGet package, next, we are going to add a new connection folder.
Creating Connector folder and adding ConnectionToEs class

After creating the folder, next, we are going to add ConnectionToEs class.
In this class, we are going to create a connection to elastic search instance. As you can see in the below code, we have provided elastic search URI http://localhost:9200/".

Code Snippet

    using Elasticsearch.Net;  
    using Nest;  
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
      
    namespace WebElasticSearch.Connector  
    {  
        public class ConnectionToEs  
        {  
            #region Connection string to connect with Elasticsearch  
      
            public ElasticClient EsClient()  
            {  
                var nodes = new Uri[]  
                {  
                    new Uri("http://localhost:9200/"),  
                };  
      
                var connectionPool = new StaticConnectionPool(nodes);  
                var connectionSettings = new ConnectionSettings(connectionPool).DisableDirectStreaming();  
                var elasticClient = new ElasticClient(connectionSettings);  
      
                return elasticClient;  
            }  
     
            #endregion Connection string to connect with Elasticsearch  
        }  
    }  

After creating the connection class, next, we are going to add a Controller and create View for search.

Add Controller “AllSearch”

Adding a controller with name “AllSearch”.

After adding the Controller, next, we are going to add an action method and in the constructor, we are going to instantiate the connection object.

Adding Action Method
In this part, we are going to add Action method “Search” and create an instance of the ConnectionToEs class.

Code Snippet
    using System.Web.Mvc;  
    using WebElasticSearch.Connector;  
      
    namespace WebElasticSearch.Controllers  
    {  
        public class AllSearchController : Controller  
        {  
            private readonly ConnectionToEs _connectionToEs;  
            public AllSearchController()  
            {  
                _connectionToEs = new ConnectionToEs();  
            }  
      
            [HttpGet]  
            public ActionResult Search()  
            {  
                return View("Search");  
            }  
        }  
    }  

After adding “Search” Action Method, we are going to add a View for that action method.

Now, we are going to design the View.

Designing View

In this part, we are going to design the View with 2 textboxes.

    jobtitle
    nationalidnumber

Below is document of “humanresource” index in which, first we are going to create a search on both these parameters.


After designing the search View, next, we are going to add a class “humanresource” and properties similar to “humanresource” index and type “doc”.

Adding Class similar to “Humanresource” Index and type “Doc”
    public class Humanresources  
    {  
     public string nationalidnumber { get; set; }  
     public string LoginID { get; set; }  
     public string OrganizationNode { get; set; }  
     public int? OrganizationLevel { get; set; }  
     public string jobtitle { get; set; }  
     public string BirthDate { get; set; }  
     public string MaritalStatus { get; set; }  
     public string Gender { get; set; }  
     public DateTime? HireDate { get; set; }  
     public bool? SalariedFlag { get; set; }  
     public int? VacationHours { get; set; }  
     public int? SickLeaveHours { get; set; }  
     public bool? CurrentFlag { get; set; }  
     public string rowguid { get; set; }  
     public DateTime? ModifiedDate { get; set; }  }

After adding humanresource class next we are going to add “DataSearch” Action Method which will take both this parameter as input and provide response in json.

Adding DataSearch Action Method
The request to elastic search we are going to send using “Nest” Client.

In this action Method the first thing we have done is to connect to elastic search using connectionEs class, then we have provided index “humanresources” and type “doc”, next we can provide size of document as output I have provided as 50, at last comes query in this we are using “match” query for that we are passing field jobtitle and in query we are going to pass value which we have searched.

Code Snippet
    public JsonResult DataSearch(string jobtitle, string nationalIDNumber)  
        {  
            var responsedata = _connectionToEs.EsClient().Search<Humanresources>(s => s  
                                    .Index("humanresources")  
                                    .Type("doc")  
                                    .Size(50)  
                                    .Query(q => q  
                                        .Match(m => m  
                                            .Field(f => f.jobtitle)  
                                            .Query(jobtitle)  
                                        )  
                                    )  
                                );  
      
            var datasend = (from hits in responsedata.Hits  
                            select hits.Source).ToList();  
      
            return Json(new { datasend, responsedata.Took }, behavior: JsonRequestBehavior.AllowGet);  
        }  

After creating Action Method and setting up search with Nest, next we are going to call this Action Method using AJAX and then display this result on View. Since we get the response as JSON, I am going to use a client-side grid from DevExpress.

Calling Datasearch Action Method using Ajax and Displaying Response in Grid

Code Snippet
    <script>  
        $(document).ready(function () {  
      
            $("#btnsubmit").on("click", function () {  
      
                if ($("#txtjobTitle").val() === "" && $("#txtnationalIDNumber").val() === "") {  
                    alert("Provide Details to Search !");  
                }  
                else {  
      
                    var obj = {};  
                    obj.jobTitle = $.trim($("#txtjobTitle").val());  
                    obj.nationalIDNumber = $.trim($("#txtnationalIDNumber").val());  
      
                    var apiUrl = "@Url.Action("DataSearch", "AllSearch")";  
      
                    $.ajax({  
                        type: "POST",  
                        contentType: 'application/json',  
                        url: apiUrl,  
                        dataType: "json",  
                        data: JSON.stringify(obj),  
                        crossDomain: true,  
                        success: function (data) {  
                            var response = data;  
      
                            if (data.datasend.length <= 0) {  
                                alert("No Data Found!!");  
                            } else {  
      
                                var timetook = data.Took;  
                                $('div.total-title').text(timetook + " millisecond");  
      
                                $("#gridContainer").dxDataGrid({  
                                    dataSource: data.datasend,  
                                    showColumnLines: false,  
                                    showRowLines: true,  
                                    rowAlternationEnabled: true,  
                                    showBorders: true,  
                                    paging: {  
                                        pageSize: 50  
                                    },  
                                    scrolling: {  
                                        mode: "infinite" // or "virtual" | "infinite"  
                                    },  
                                    pager: {  
                                        showPageSizeSelector: false,  
                                        allowedPageSizes: [5, 10, 20],  
                                        showInfo: true  
                                    },  
                                    columns: [  
                                        {  
                                            caption: "JobTitle",  
                                            width: 350,  
                                            fixed: true,  
                                            dataField: "jobtitle"  
                                        },  
                                        {  
                                            caption: "NationalIDNumber",  
                                            width: 300,  
                                            fixed: true,  
                                            dataField: "nationalidnumber"  
                                        },  
                                         "MaritalStatus",  
                                         "Gender",  
                                         "SalariedFlag",  
                                         "VacationHours",  
                                         "SickLeaveHours",  
                                         "CurrentFlag"  
                                    ]  
                                });  
      
                            }  
                        },  
                        error: function (xhr, err) {  
                            alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);  
                            alert("responseText: " + xhr.responseText);  
                        }  
      
                    });  
      
                }  
      
            });  
      
        });  
      
    </script>  

Markup of Grid
    <div class="panel panel-default">  
        <div class="panel-heading">Output</div>  
        <div class="panel-body">  
            <div class="row">  
                <div class="col-lg-12">  
                    <div id="gridContainer"></div>  
                </div>  
            </div>  
        </div>  
    </div>   

We have set up everything. Let’s run the code and see the output.

Output

Let’s see in Debug Mode how it works.

Searching Values



Getting Response

Single Document View

Let us now make the search conditional, i.e., the user can use any combination to search.

If the user searches data by Jobtitle only, then he will get response according to jobtitle. If a user does search with nationalidnumber, then he will get response according to it. Finally, the combination of both (Jobtitle+ nationalidnumber) can also be used to search, then the user will get response according to it.

Code Snippet
    public JsonResult DataSearch(string jobtitle, string nationalIDNumber)  
          {  
      
              if (!string.IsNullOrEmpty(jobtitle) && !string.IsNullOrEmpty(nationalIDNumber))  
              {  
                  var responsedata = _connectionToEs.EsClient().Search<Humanresources>(s => s  
                                   .Index("humanresources")  
                                   .Type("doc")  
                                   .Size(50)  
                                   .Query(q => q  
                                       .Match(m => m  
                                           .Field(f => f.jobtitle)  
                                           .Query(jobtitle)  
                                       )  
                                       && q  
                                       .Match(m => m  
                                           .Field(f => f.nationalidnumber)  
                                           .Query(nationalIDNumber)  
                                   ))  
                               );  
      
                  var datasend = (from hits in responsedata.Hits  
                                  select hits.Source).ToList();  
      
                  return Json(new { datasend, responsedata.Took }, behavior: JsonRequestBehavior.AllowGet);  
      
              }  
              else if (!string.IsNullOrEmpty(jobtitle))  
              {  
                  var responsedata = _connectionToEs.EsClient().Search<Humanresources>(s => s  
                                  .Index("humanresources")  
                                  .Type("doc")  
                                  .Size(50)  
                                  .Query(q => q  
                                      .Match(m => m  
                                          .Field(f => f.jobtitle)  
                                          .Query(jobtitle)  
                                      )));  
      
                  var datasend = (from hits in responsedata.Hits  
                                  select hits.Source).ToList();  
      
                  return Json(new { datasend, responsedata.Took }, behavior: JsonRequestBehavior.AllowGet);  
              }  
              else if (!string.IsNullOrEmpty(nationalIDNumber))  
              {  
                  var responsedata = _connectionToEs.EsClient().Search<Humanresources>(s => s  
                                  .Index("humanresources")  
                                  .Type("doc")  
                                  .Size(50)  
                                  .Query(q => q  
                                      .Match(m => m  
                                          .Field(f => f.nationalidnumber)  
                                          .Query(nationalIDNumber)  
                                      )));  
                  var datasend = (from hits in responsedata.Hits  
                                  select hits.Source).ToList();  
      
                  return Json(new { datasend, responsedata.Took }, behavior: JsonRequestBehavior.AllowGet);  
              }  
              return Json(data: null, behavior: JsonRequestBehavior.AllowGet);  
      
          }  


Output


These are simple examples which will help you to start using elastic search with ASP.NET Application. There are lots of filters and ways to write query in Elastic using “Nest” in ASP.NET.

Finally, we have learned how to simply query elastic search using “Nest” Client and display data in grid.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Simple Login Application using Sessions in ASP.NET MVC

clock September 1, 2023 10:10 by author Peter

Step: Design your Database
Create the UserProfile table using the following script.
    Create Table UserProfile  
        (  
            UserId int primary key identity(1, 1),  
            UserName varchar(50),  
            Password varchar(50),  
            IsActive bit  
        ) 



Insert user records using the following script.
    Insert into UserProfile  
    Select 'peter', 'pete1234', 1 Union All  
    Select 'scott', 'scott1234', 1 Union All  
    Select 'laura', 'laura1234', 1


Step 1: Create Project
Go to FILE, New, then click on Project.

Select Visual C#, Web under Installed templates. After that select ASP.NET MVC Web Application, then mention the Application Name (MvcLoginAppDemo) and Solution Name as you wish, then click OK.

Under Project template select a template as Basic, then Click OK.

Step 2: Add Entity Data Model
Go to Solution Explorer, Right Click on Project, Add, then select ADO.NET Entity Data Model.

Give it a meaningful model name and then click on Add.

Select Generate from database and then click on Next.


Click on New Connection,

After clicking on New Connection, we have to provide the following Connection Properties in the following wizard.
    Provide the Server name.
    Select the "Use SQL Server Authentication" radio button.
    Enter the User name and Password in the password text box.
    Check the "Save my password" checkbox.
    Select the "Select or enter a database name:" radio button.
    Select the database to which you want to set the connection.
    Click on the "Test Connection" button to ensure the connection can be established.
    Then click OK.

Select radio button: Yes include the sensitive data in the connection string. Choose your database objects, as in the following image. Click on Finish. At this point UserProfie entity will be created.

Step 3: Add a Controller
Go to Solution Explorer, Right click on Controller folder, Add and then click on Controller.
( Or ) Simply use shortcut key Ctrl + M, Ctrl + C,

Provide the Controller Name, and Scaffolding template as Empty MVC Controller. Then click on Add.

Write the following code in HomeController.
    using System.Linq;  
    using System.Web.Mvc;  
      
    namespace MvcLoginAppDemo.Controllers  
    {  
        public class HomeController: Controller  
        {  
            public ActionResult Login()  
            {  
                return View();  
            }  
      
            [HttpPost]  
            [ValidateAntiForgeryToken]  
            public ActionResult Login(UserProfile objUser)   
            {  
                if (ModelState.IsValid)   
                {  
                    using(DB_Entities db = new DB_Entities())  
                    {  
                        var obj = db.UserProfiles.Where(a => a.UserName.Equals(objUser.UserName) && a.Password.Equals(objUser.Password)).FirstOrDefault();  
                        if (obj != null)  
                        {  
                            Session["UserID"] = obj.UserId.ToString();  
                            Session["UserName"] = obj.UserName.ToString();  
                            return RedirectToAction("UserDashBoard");  
                        }  
                    }  
                }  
                return View(objUser);  
            }  
      
            public ActionResult UserDashBoard()  
            {  
                if (Session["UserID"] != null)  
                {  
                    return View();  
                } else  
                {  
                    return RedirectToAction("Login");  
                }  
            }  
        }  
    }  


Step 4: Create Views
Create View for Login Action Method
 
Right click on the Login Action method, then click on Add View as in the following picture.

Create Strongly Typed View
    View Name must be an action method name.
    Select view engine as Razor.
    Select Create a strongly typed view CheckBox .
    Select Model class as UserProfile (MvcLoginAppDemo)
    Select Scaffold template as Empty
    Click on Add

And write the following code in Login.cshtml (view).
    @model MvcLoginAppDemo.UserProfile  
      
    @{  
    ViewBag.Title = "Login";  
    }  
      
    @using (Html.BeginForm("Login", "Home", FormMethod.Post))  
    {  
    <fieldset>  
    <legend>Mvc Simple Login Application Demo</legend>  
      
    @Html.AntiForgeryToken()  
    @Html.ValidationSummary(true)  
    @if (@ViewBag.Message != null)  
    {  
    <div style="border: 1px solid red">  
    @ViewBag.Message  
    </div>  
    }  
    <table>  
    <tr>  
    <td>@Html.LabelFor(a => a.UserName)</td>  
    <td>@Html.TextBoxFor(a => a.UserName)</td>  
    <td>@Html.ValidationMessageFor(a => a.UserName)</td>  
    </tr>  
    <tr>  
    <td>  
    @Html.LabelFor(a => a.Password)  
    </td>  
    <td>  
    @Html.PasswordFor(a => a.Password)  
    </td>  
    <td>  
    @Html.ValidationMessageFor(a => a.Password)  
    </td>  
    </tr>  
    <tr>  
    <td></td>  
    <td>  
    <input type="submit" value="Login" />  
    </td>  
    <td></td>  
    </tr>  
    </table>  
    </fieldset>  
    }  


Create View for UserDashBoard Action method same as login view. And write the following code in UserDashBoard.cshtml (View).
    @ {  
        ViewBag.Title = "UserDashBoard";  
    }  
      
    < fieldset >  
        < legend > User DashBoard < /legend>  
      
    @if(Session["UserName"] != null) { < text >  
            Welcome @Session["UserName"].ToString() < /text>  
    } < /fieldset>  


Step 5: Set as StartUp Page
Go to Solution Explorer, Project, App_Start, then RouteConfig.cs  and change the action name from Index to Login (Login.cshtml as start up page).

Step 6: Run the Application
Provide the user credentials and click on OK. If you provide the valid user credentials then the user name will be displayed on your dashboard.



About HostForLIFE.eu

HostForLIFE.eu 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in