European ASP.NET MVC Hosting

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

ASP.NET MVC 6 Hosting - HostForLIFEASP.NET :: Display Bootstrap Alerts Dynamically From ASP.NET Core 3.1 MVC

clock May 24, 2021 07:35 by author Peter

This article introduces how to display bootstrap alerts dynamically from an ASP.NET Core 3.1 MVC Application. Bootstrap provides us with an easy way to create predefined alerts. Bootstrap alerts are available for any length of text, as well as an optional close button. An example of a bootstrap alert is given below.

    <div class="alert alert-success alert-dismissible">    
       <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>    
       <strong>Success!</strong> This alert box could indicate a successful or positive action.    
     </div>   
 

Let's follow the below steps to show the alerts dynamically from a simple ASP.NET Core 3.1 MVC Application.
 
Step 1
Create an ASP.NET Core 3.1 MVC Web App.


Step 2
Add a new folder and add an Enum into that folder and give a suitable name like this.


Step 3
Now create a common service like this.

The code snippet for the CommonServices.cs class is given below. A new static method ‘ShowAlert’ is added here which takes two parameters and returns html as string.
    public class CommonServices {  
        public static string ShowAlert(Alerts obj, string message) {  
            string alertDiv = null;  
            switch (obj) {  
                case Alerts.Success:  
                    alertDiv = "<div class='alert alert-success alert-dismissable' id='alert'><button type='button' class='close' data-dismiss='alert'>×</button><strong> Success!</ strong > " + message + "</a>.</div>";  
                    break;  
                case Alerts.Danger:  
                    alertDiv = "<div class='alert alert-danger alert-dismissible' id='alert'><button type='button' class='close' data-dismiss='alert'>×</button><strong> Error!</ strong > " + message + "</a>.</div>";  
                    break;  
                case Alerts.Info:  
                    alertDiv = "<div class='alert alert-info alert-dismissable' id='alert'><button type='button' class='close' data-dismiss='alert'>×</button><strong> Info!</ strong > " + message + "</a>.</div>";  
                    break;  
                case Alerts.Warning:  
                    alertDiv = "<div class='alert alert-warning alert-dismissable' id='alert'><button type='button' class='close' data-dismiss='alert'>×</button><strong> Warning!</strong> " + message + "</a>.</div>";  
                    break;  
            }  
            return alertDiv;  
        }  
    }   


Now let’s call this method from a controller which is saving records in the database. The following is the code snippet for the controller.
    // POST: EmployeeController/Create    
    [HttpPost]  
    [ValidateAntiForgeryToken]  
    public ActionResult Create([FromForm] EmployeeViewModel collection) {  
        try {  
            int result = 0;  
            if (ModelState.IsValid) {  
                Employee objEmp = new Employee();  
                objEmp.EmpName = collection.EmpName;  
                objEmp.Address = collection.Address;  
                objEmp.Email = collection.Email;  
                objEmp.Phone = collection.Phone;  
                objEmp.BankAccountNo = collection.BankAccountNo;  
                objEmp.CreatedOn = DateTime.Now;  
                objEmp.CreatedBy = "SYSTEM";  
                objEmp.ModifiedOn = null;  
                objEmp.ModifiedBy = null;  
                result = _empRepo.Add(objEmp).Result;  
                //return RedirectToAction("Index");    
                if (result > 0) {  
                    ViewBag.Alert = CommonServices.ShowAlert(Alerts.Success, "Employee added");  
                } else ViewBag.Alert = CommonServices.ShowAlert(Alerts.Danger, "Unknown error");  
            }  
            return PartialView("_Create");  
        } catch {  
            return View();  
        }  
    }   


Code Explanation
 In post type method we pass EmployeeViewModel class as a parameter as a model name that gets all data from the user.
    _empRepo.Add() is a custom method used to save the Employee records. ( Repository Pattern is used to save a record here. You can download complete source code from the GitHub link given below ).

Step 4
Now add the below line in the view like this. It helps to render the HTML from the ViewBag string returned from the static method.
    @Html.Raw(@ViewBag.Alert) 


The following is the complete code snippet for the view.
    @model CodeSample.Models.EmployeeViewModel  
    @{  
        ViewData["Title"] = "Add Employee";  
        Layout = "~/Views/Shared/_Layout.cshtml";  
    }  
      
    <h4>Add Employee</h4>  
    <hr />  
    <div class="row">     
        <div class="col-md-4">  
            <form asp-action="Create" asp-controller="Employee" method="post">  
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
                <div class="form-group">  
                    <label asp-for="EmpName" class="control-label">Enter employee name</label>  
                    <input asp-for="EmpName" class="form-control" />  
                    <span asp-validation-for="EmpName" class="text-danger"></span>  
                </div>  
                <div class="form-group">  
                    <label asp-for="Email" class="control-label">Enter email</label>  
                    <input asp-for="Email" class="form-control" />  
                    <span asp-validation-for="Email" class="text-danger"></span>  
                </div>  
                <div class="form-group">  
                    <label asp-for="Phone" class="control-label">Enter Phone No.</label>  
                    <input asp-for="Phone" class="form-control" />  
                    <span asp-validation-for="Phone" class="text-danger"></span>  
                </div>  
                <div class="form-group">  
                    <label asp-for="Address" class="control-label">Enter Address</label>  
                    <textarea asp-for="Address" class="form-control"></textarea>  
                    <span asp-validation-for="Address" class="text-danger"></span>  
                </div>  
                <div class="form-group">  
                    <label asp-for="BankAccountNo" class="control-label">Enter Bank Account No.</label>  
                    <input asp-for="BankAccountNo" class="form-control" />  
                    <span asp-validation-for="BankAccountNo" class="text-danger"></span>  
                </div>  
                <div class="form-group">  
                    <input type="submit" id="SaveEmp" value="Create" class="btn btn-primary" />  
                </div>  
            </form>  
        </div>  
     </div>  
    <div class="row">  
        <div class="col-md-12">  
            <div class="form-group">  
                @Html.Raw(@ViewBag.Alert)  
            </div>  
        </div>  
    </div>  
      
     <div><a asp-action="Index">Back to List</a></div>  
      
     @section Scripts {  
      
            @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
     }  

Now if something goes wrong and the application is unable to insert the record in the database, it will show an error alert like this.


Else it will show a success alert like this.


Here we saw how to display a bootstrap alert dynamically from ASP.NET Core 3.1 MVC Application. Hope you like this article and get some information from it.
 

 

 

 

 

 

 



ASP.NET MVC 6 Hosting - HostForLIFEASP.NET :: Install Bootstrap In ASP.NET MVC 5

clock May 19, 2021 08:29 by author Peter

Today I will share the way to install Bootstrap in ASP.NET MVC5 using Visual Studio 2019. Setup Bootstrap 3.3.1 to ASP.NET MVC 5
 
Right-click Project -> Manager NuGet Packages -> Click icon setting configuration, add package source.
 
https://api.nuget.org/v3/index.json


Continue by adding a package source (following image)


You search keyword “bootstrap” and then install


You can see bootstrap in project after a successful installation.


Okay, installation is successful!
You can use bootstrap in Layout file of Views/Shared/_LayoutHome.cshtml directory. (Note you add css,javascript to file)

    <link rel="stylesheet" href="~/Content/bootstrap.min.css" />  
    <script src="~/Scripts/jquery-3.3.1.min.js"></script>  
    <script src="~/Scripts/bootstrap.min.js"></script>  

Example - Views/Shared/_LayoutHome.cshtml

    <!DOCTYPE html>  
    <html>  
    <head>  
        <meta name="viewport" content="width=device-width" />  
        <title>@ViewBag.Title</title>  
        <link rel="stylesheet" href="~/Content/bootstrap.min.css" />  
        <script src="~/Scripts/jquery-3.3.1.min.js"></script>  
        <script src="~/Scripts/bootstrap.min.js"></script>  
    </head>  
    <body>  
        <div>  
            @RenderBody()  
        </div>  
    </body>  
    </html>  

Views/Home/Index.cshtml

    <div class="container">  
        <div class="row">  
            <div class="col-md-12">  
                <h2>@ViewBag.title</h2>  
                <a href="https://hostforlifeasp.net" class="btn btn-success">https://hostforlifeasp.net/</a>  
            </div>  
        </div>  
    </div>  

Ok, we successfully installed bootstrap in ASP.NET MVC 5

 



ASP.NET MVC 6 Hosting - HostForLIFEASP.NET :: GET and POST Calls to Controller's Method in MVC

clock May 6, 2021 07:37 by author Peter

In this article I am going to cover some really interesting material that is very useful today in web application development. You will learn how to make jQuery Ajax GET and POST calls to controller methods.

When we use jQuery Ajax to access a server (controller's method) without reloading the web page we have two choices for how to pass the information for the request to the server (controller's method). These two options are to use either GET or POST.
 
Note: Before beginning with the code, ensure you are using the jQuery library before the GET or POST script.
 
GET
GET is used to request data from a specified resource. With all the GET request we pass the URL which is compulsory, however it can take the following overloads.
    .get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ).done/.fail  

Now, let's try to use GET in MVC application.
 
GET call to Controller's Method that will return string data
 
Let's imagine we have the following method in the controller:
    public string TellMeDate()  
    {  
        return DateTime.Today.ToString();  
    }  


This method will return string data (date-time) when we call it, let's make an async call using jQuery Ajax.
    <p id="rData">  
    </p>   
    <script type="text/jscript">  
        var url = "/Home/TellMeDate";  
        $.get(url, null, function (data) {  
            $("#rData").html(data);  
        });  
    </script>  


When the page gets loaded, jQuery Ajax will generate an Ajax GET request/call. The first parameter is the URL and the second is data (this is an optional, even we can avoid typing "null") and the third is the success function when the response is received. The success function takes one parameter "data" that holds the string content and we attached this content to a DOM element.
 
If you want to generate an Ajax GET request when the user clicks a button then can use the following instead:
    <script type="text/jscript">  
        $('#ButtonID').click(function () {  
            var url = "/Home/TellMeDate";  
            $.get(url, null, function (data) {  
                $("#rData").html(data);  
            });  
        })  
    </script>  


If you run the application, you will see the following output:

GET call with parameter to Controller's Method that will return string data
 
Let's imagine we have the following method in the controller:
    public string WelcomeMsg(string input)  
    {  
        if (!String.IsNullOrEmpty(input))  
            return "Please welcome " + input + ".";  
        else  
            return "Please enter your name.";  
    }   


This method will accept a parameter and will return string data (a welcome message or instruction message) when we call it. Now, let's make an async call to this method using jQuery Ajax.
    <p>  
        Enter you name @Html.TextBox("Name")  
        <input type="submit" id="SubmitName" value="Submit"/>  
    </p>   
    <script type="text/jscript">  
        $('#SubmitName').click(function () {  
            var url = "/Home/WelcomeMsg";  
            var name = $('#Name').val();  
            $.get(url, { input: name }, function (data) {  
                $("#rData").html(data);  
            });  
        })  
    </script>   


As you can see, when we click the button after typing a name in the TextBox, jQuery Ajax will generate an Ajax GET request/call. Notice that the second parameter to the "get" function now contains a key { input: name } (parameter). This example supplies one parameter, but can be extended to provide multiple parameters.

GET call with parameter to Controller's Method that will return JSON data
 
The Controller's method we used above returns simple strings. Now, to deal with complex data we need JSON. The following method will return a JsonResult having the customer's ContactName and Address from NorthwindEntities. I am using the Northwind database and EF Database First approach in this sample.
    public JsonResult CustomerList(string Id)  
    {  
        NorthwindEntities db = new NorthwindEntities();  
        var result = from r in db.Customers  
                        where r.Country == Id  
                        select new { r.ContactName, r.Address };  
        return Json(result, JsonRequestBehavior.AllowGet);  
    }   


The above method will accept Id as a parameter and return a "JsonResult". This action method can be called using the following jQuery Ajax GET call:
    <p id="rData">  
    </p>   
    <p>  
        Enter country name @Html.TextBox("Country")  
        <input type="submit" id="GetCustomers" value="Submit"/>  
    </p>   
    <script type="text/jscript">  
        $('#GetCustomers').click(function () {  
            $.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {   
                var items = '<table><tr><th>Name</th><th>Address</th></tr>';  
                $.each(data, function (i, country) {  
                    items += "<tr><td>" + country.ContactName + "</td><td>" + country.Address + "</td></tr>";  
                });  
                items += "</table>";   
                $('#rData').html(items);  
            });  
        })  
    </script>   


As you can see, when we click the button after typing a country name in the TextBox, jQuery Ajax will generate an Ajax GET request/call. Notice that the "getJSON" function now contains an URL in the format "/Controller/ActionMethod/Key", here the key (parameter) is the supplied country name.

Using Firebug we can sniff the response. We have used a TextBox where we typed the country name and clicked on a button to get the list of customers.
 
Alternatively, we can populate the list of countries in the dropdownlist box and then when the user selects the country name from the dropdownlist, we can display the list of customers.   

Here is the controller that will populate the country list in the dropdownlist box:
    public ActionResult About()  
    {  
        var result = from r in db.Customers  
                        select r.Country;  
        ViewBag.Country = result;   
        return View();  
    }   


Now, once we have a list of countries in the dropdownlist box, we can implement an Ajax GET request/call. Here it is with a complete view page.
    @Html.DropDownListFor(model => model.Country, new SelectList(ViewBag.Country), "Select Country")   
    <p id="rData">  
    </p>   
    @section Scripts {  
        <script type="text/jscript">  
            $('#Country').click(function () {  
                $.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {   
                    var items = '<table><tr><th>Name</th><th>Address</th></tr>';  
                    $.each(data, function (i, country) {  
                        items += "<tr><td>" + country.ContactName + "</td><td>" + country.Address + "</td></tr>";  
                    });  
                    items += "</table>";   
                    $('#rData').html(items);  
                });  
            })  
        </script>  
    }   

Everything remains the same as in the TextBox version above.
 
POST
POST is used to submit data to be processed to a specified resource. With all the POST requests we pass the URL which is compulsory and the data, however it can take the following overloads.  
    .post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )   

Now, let's try to use POST in a MVC application.
 
POST call to Controller's Method to save TextBox data (not form)
 
There are various ways to POST form data to a method but in the example given below I'm not going to use any form. I will just use two textboxes and a submit button, when the user clicks the button I want to save the data using a jQuery Ajax POST call. So, here is the method accepting the two parameters for name and address:
    [HttpPost]  
    public string SubmitSubscription(string Name, string Address)  
    {  
        if (!String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(Address))  
            //TODO: Save the data in database  
            return "Thank you " + Name + ". Record Saved.";  
        else  
            return "Please complete the form.";             
    }   


We can implement method above to save the data in the database, it will also return the response back to the client. Here is the jQuery Ajax POST function:
    <h2>Subscription</h2>   
    <p>  
        Enter your name  
        <br />  
        @Html.TextBox("Name")  
    </p>  
    <p>  
        Enter your address  
        <br />  
        @Html.TextBox("Address")  
    </p>   
    <input type="button" value="Save" id="Save" />  
    <span id="msg" style="color:red;"/>   
    <script type="text/javascript">  
        $('#Save').click(function () {  
            var url = "/Home/SubmitSubscription";  
            var name = $("#Name").val();  
            var address = $("#Address").val();  
            $.post(url, { Name: name, Address: address }, function (data) {  
                $("#msg").html(data);  
            });  
        })  
    </script>   


POST call to Controller's Method to save form data
In case above we don't have a form, so I have used two individual properties/parameters (name and address) with a jQuery Ajax POST call and also on the method side, but this approach will be painful since the number of properties increase. In this case we can use the model approach that will allow us to work with intelisense. So, let's go and create the "Subscription" model class with two properties.
    public class Subscription  
    {  
        public string Name { get; set; }  
        public string Address { get; set; }  
    }  

Now that we have the model we can create our controller method:
    [HttpPost]  
    public string SubmitSubscription(Subscription subs)  
    {  
        if (!String.IsNullOrEmpty(subs.Name) && !String.IsNullOrEmpty(subs.Address))  
            //TODO: Save the data in database  
            return "Thank you " + subs.Name + ". Record Saved.";  
        else  
            return "Please complete the form.";             
    }  

Still the same, just using a model instead of individual properties.
    <h2>Subscription</h2>   
    <form id="subscriptionForm" action="/Home/SubmitSubscription" method="post">  
    <p>  
        Enter your name  
        <br />  
        @Html.TextBox("Name")  
    </p>  
    <p>  
        Enter your address  
        <br />  
        @Html.TextBox("Address")  
    </p>   
    <input type="button" value="Save" id="Save" />  
    <span id="msg" style="color:red;"/>  
    </form>   
    @section Scripts{  
        <script type="text/javascript">  
            $('#Save').click(function () {   
                var form = $("#subscriptionForm");  
                var url = form.attr("action");  
                var formData = form.serialize();  
                $.post(url, formData, function (data) {  
                    $("#msg").html(data);  
                });  
            })  
        </script>  
    }  


Noting new, everything is the same, just a few changes that allow us to work with a form.



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