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 :: ASP.NET ZXing.Net Implementation In ASP.NET MVC

clock July 28, 2021 07:54 by author Peter

ZXing.NET is a library that supports decoding and generating of barcodes (like QR Code, PDF 417, EAN, UPC, Aztec, Data Matrix, Codabar) within images. In this repository, I will implement it in ASP.NET MVC 5 application.

I create the following things with ZXing.NET,

Create QR Codes for any text entered by the user.
Create QR Codes Code Files for any text which the user enters. I will save these QR Code files in ‘qrr’ folder which is placed at the root of the application.
Read all the QR Code files and Decoding them.

Installation

To use the ZXing.NET library you need to install the ZXing.Net package from NuGet.

PM> Install-Package ZXing.Net

Create QR Creating QR Codes

In your controller import the following namespaces,
using System;
using System.Collections.Generic;
using System.IO;
using ZXing;
using ZXing.QrCode;
using System.Web.Mvc;
using System.Drawing;

Next, add 2 Index Action methods in your controller whose code is given below,
public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult Index(string qrText)
{
Byte[] byteArray;
var width = 250; // width of the Qr Code   
var height = 250; // height of the Qr Code   
var margin = 0;
var qrCodeWriter = new ZXing.BarcodeWriterPixelData
{
    Format = ZXing.BarcodeFormat.QR_CODE,
    Options = new QrCodeEncodingOptions
    {
        Height = height,
        Width = width,
        Margin = margin
    }
};
var pixelData = qrCodeWriter.Write(qrText);

// creating a bitmap from the raw pixel data; if only black and white colors are used it makes no difference   
// that the pixel data ist BGRA oriented and the bitmap is initialized with RGB   
using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))
{
    using (var ms = new MemoryStream())
    {
        var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
        try
        {
            // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image   
            System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
        }
        finally
        {
            bitmap.UnlockBits(bitmapData);
        }
        // save to stream as PNG   
        bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        byteArray = ms.ToArray();
    }
}
return View(byteArray);
}


Explanation
The [HttpPost] version of the Index Action method gets the text (for which the QR Code has to be generated) in the ‘qrText’ string variable defined in its parameter. This implementation remains the same for versions like Web Forms, Blazor and .NET Core also. I have checked this thing myself, so if you wish to implement ZXing.NET on these frameworks then the codes will remain the same.

The QR Code is generated for the text and its byte array is returned to the View where the bitmap code is displayed from this byte[] array value.

Create the Index View and add the following code to it,
@model Byte[]
@using (Html.BeginForm(null, null, FormMethod.Post))
{
<table>
    <tbody>
        <tr>
            <td>
                <label>Enter text for creating QR Code</label>
            </td>
            <td>
                <input type="text" name="qrText" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <button>Submit</button>
            </td>
        </tr>
    </tbody>
</table>
}
@{
if (Model != null)
{
    <h3>QR Code Successfully Generated</h3>
    <img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(Model))" />
}
}


Explanation
The View has a form where the user enters the string in the text box. The generated QR Code is displayed as an image by the img tag as shown below,
<img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(Model))" />

Testing
Run your application and enter any text in the text box. On clicking the submit button the QR Code will be created and displayed. See the below video where I am generating the QR Code,

Create QR Creating QR Codes
You can also create QR Code files. These QR Code files will be stored inside the ‘qrr’ folder on the root of your application.

First, create a new folder called ‘qrr’ inside the application root folder.

Next create ‘GenerateFile()’ index methods inside the Controller, as shown below,
public ActionResult GenerateFile()
{
return View();
}

[HttpPost]
public ActionResult GenerateFile(string qrText)
{
Byte[] byteArray;
var width = 250; // width of the Qr Code   
var height = 250; // height of the Qr Code   
var margin = 0;
var qrCodeWriter = new ZXing.BarcodeWriterPixelData
{
    Format = ZXing.BarcodeFormat.QR_CODE,
    Options = new QrCodeEncodingOptions
    {
        Height = height,
        Width = width,
        Margin = margin
    }
};
var pixelData = qrCodeWriter.Write(qrText);

// creating a bitmap from the raw pixel data; if only black and white colors are used it makes no difference   
// that the pixel data ist BGRA oriented and the bitmap is initialized with RGB   
using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))
{
    using (var ms = new MemoryStream())
    {
        var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
        try
        {
            // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image   
            System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
        }
        finally
        {
            bitmap.UnlockBits(bitmapData);
        }

        // save to folder
        string fileGuid = Guid.NewGuid().ToString().Substring(0, 4);
        bitmap.Save(Server.MapPath("~/qrr") + "/file-" + fileGuid + ".png", System.Drawing.Imaging.ImageFormat.Png);

        // save to stream as PNG   
        bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        byteArray = ms.ToArray();
    }
}
return View(byteArray);
}

The ‘GenerateFile’ action method is very much similar to the earlier Index Action method. Only one change remains, which is the saving of the QR Code file inside the ‘qrr’ folder. The below 2 code lines do this saving work,
string fileGuid = Guid.NewGuid().ToString().Substring(0, 4);
bitmap.Save(Server.MapPath("~/qrr") + "/file-" + fileGuid + ".png", System.Drawing.Imaging.ImageFormat.Png);


Also, you need to create the GenerateFile View and add the following code to it. The GenerateFile View is totally the same as the Index View,
@model Byte[]
@using (Html.BeginForm(null, null, FormMethod.Post))
{
<table>
    <tbody>
        <tr>
            <td>
                <label>Enter text for creating QR Code</label>
            </td>
            <td>
                <input type="text" name="qrText" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <button>Submit</button>
            </td>
        </tr>
    </tbody>
</table>
}
@{
if (Model != null)
{
    <h3>QR Code Successfully Generated</h3>
    <img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(Model))" />
}
}

Testing
open the URL of the GenerateFile Action method and enter any value in the text box and click the ‘Submit button. You will see the QR Code gets created and saved in a .png file inside the ‘qrr’ folder.
Reading all the QR Code files and Decoding their QR Code

Now let us read all the QR Code files and decode their QR Code values.

Create ViewFile Action method in your controller whose code is given below,
public ActionResult ViewFile()
{
List<KeyValuePair<string, string>> fileData = new List<KeyValuePair<string, string>>();
KeyValuePair<string, string> data;

string[] files = Directory.GetFiles(Server.MapPath("~/qrr"));
foreach (string file in files)
{
    // create a barcode reader instance
    IBarcodeReader reader = new BarcodeReader();
    // load a bitmap
    var barcodeBitmap = (Bitmap)Image.FromFile(Server.MapPath("~/qrr") + "/" + Path.GetFileName(file));
    // detect and decode the barcode inside the bitmap
    var result = reader.Decode(barcodeBitmap);
    // do something with the result
    data = new KeyValuePair<string, string>(result.ToString(), "/qrr/" + Path.GetFileName(file));
    fileData.Add(data);
}
return View(fileData);
}


Explanation
Get all the files inside the ‘qrr’ folder by using the Directory.GetFiles() method. Then loop through each of these files using the foreach() loop and decode their QR Codes.

The decoding is done using the .Decode() method,

var result = reader.Decode(barcodeBitmap);


I have used an object of List<KeyValuePair<string, string>> type to store all the file's path and their decode values of QR Code. The object is returned to the View.

Finally, create a View called ‘ViewFile’ and add the following code to it,
@model List<KeyValuePair<string, string>>
<table>
<thead>
    <tr>
        <td>
            QR Code File
        </td>
        <td>
            QR Code File Decoded Text
        </td>
    </tr>
</thead>
<tbody>
    @foreach (KeyValuePair<string, string> k in Model)
    {
        <tr>
            <td>
                <img src="@k.Value" />
            </td>
            <td>
                @k.Key
            </td>
        </tr>
    }
</tbody>
</table>


The View takes a model of List<KeyValuePair<type and displays all the QR Code files and their decode text.

Testing
Create some QR Code files and then visit the URL of the ViewFile view. You will see the QR Code files displayed as shown by the below image,



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Integrate Facebook Ads Using ASP.NET MVC

clock July 21, 2021 07:12 by author Peter

This is a sample article to integrate Facebook login using MVC and after creating a login you can fetch data from Facebook Ads accounts. So I used this to collect data for insight, reports, etc.

Step 1
You need to start with Sign in to the Facebook developer.

Step 2
Then you need to create an app. In the Facebook developer account go to the app dashboard then click on my apps and then create an app.

Step 3
When the app is created. Click on the app and go to the settings then copy the app id and app secret for future use.

Step 4
Now let's start the coding part. First, just create a simple MVC project then add a controller to it. In the Index Method, I have added the scope, App Id, redirect URL. This method will return a URL that will redirect us to the Facebook login page.
public ActionResult Index() {
dynamic parameters = new ExpandoObject();
parameters.client_id = "enter the client id here"; //app id
parameters.redirect_uri = "enter the redirect url here";
parameters.response_type = "code";
parameters.display = "popup";
//scopes
var extendedPermissions = "ads_management,ads_read,instagram_basic,business_management,email,pages_messaging,publish_to_groups,pages_manage_metadata,pages_read_user_content,leads_retrieval,pages_read_engagement,pages_manage_posts,publish_to_groups,pages_manage_ads,instagram_basic,pages_show_list,pages_manage_engagement,read_insights"; {
    parameters.scope = extendedPermissions;
}
var _fb = new FacebookClient();
var url = _fb.GetLoginUrl(parameters);
return Redirect(url.ToString());
}


Don't forget to add this redirect URL in the Facebook developer app also, go to your app then Facebook login then settings, you'll see this screen now add the URL in the redirect URL text box and save the changes.

Now we have to retrieve user profile details.
public ActionResult Login_success() {

var _fb = new FacebookClient();
List < object > oList = new List < object > ();
FacebookOAuthResult oauthResult;
if (!_fb.TryParseOAuthCallbackUrl(Request.Url, out oauthResult)) {}
if (oauthResult.IsSuccess) {
    var WebClient = new WebClient();
    Dictionary < string, object > parameters = new Dictionary < string, object > ();
    parameters.Add("client_id", "enter client id here");
    parameters.Add("redirect_uri", "enter redirect uri here");
    parameters.Add("client_secret", "enter client secret here");
    parameters.Add("code", oauthResult.Code);
    dynamic result = _fb.Get("/oauth/access_token", parameters);
    var accessToken = result.access_token;
    _fb.AccessToken = Session["AccessToken"].ToString();
    dynamic me = _fb.Get("me?fields=first_name,middle_name,last_name,id,email");
    string email = me.email;
    string firstname = me.first_name;
    string middlename = me.middle_name;
    string lastname = me.last_name;
    string name = firstname + " " + middlename + " " + lastname;
    string id = me.id;
    FbHelper db = new FbHelper();
    db.save_User_Info(id, name, email, accessToken);
    FormsAuthentication.SetAuthCookie(email, false);
} else {}
return View();
}


That's it. I have used the same user info method to save the id, name, email, and access token of the current user in my database.
public long save_User_Info(string strUserGuid, string strName, string strEmail, string accessToken) {
long nResult = 0;
try {
    SqlParameter[] sq = {
        new SqlParameter("@user_guid", strUserGuid),
        new SqlParameter("@user_name", strName),
        new SqlParameter("@user_email", strEmail),
        new SqlParameter("@user_token", accessToken)
    };
    nResult = _helper.ExecuteStoredProcedure("usp_insert_facebook_user_Information", sq);
} catch (Exception ex) {}
return nResult;
}


At first, Facebook gives us basic permission to access profiles, email, etc. To get Facebook ads details like campaign details we need to go to the app review and then permissions and features. There you will see all the permissions, you can take permissions from there for your app. And use the below API requests to retrieve campaigns.
public ActionResult CampaignData() {
string page_Token = "enter page token here";
string page_Id = "enter page id here";
string page_post_id = "enter page post id here";
string act_ad_id = "enter account act id here";
string user_Token = "enter user token here";
string ad_Set_Id = "enter ad set id here";
var WebClient = new WebClient();
string user_url = string.Format("https://graph.facebook.com/v10.0/" + ad_Set_Id + "/insights?fields=clicks%2Cspend%2Cimpressions%2Creach&access_token=" + user_Token);
string post_url = string.Format("https://graph.facebook.com/v10.0/" + page_Id + "?fields=posts%2Cads_posts&access_token=" + page_Token);
string post_like_url = string.Format("https://graph.facebook.com/v10.0/" + page_post_id + "?fields=likes%2Ccomments%2Cshares%2Creactions%2Ctargeting%2Ctarget&access_token=" + page_Token);
string page_tagret_url = string.Format("https://graph.facebook.com/v10.0/" + act_ad_id + "/adsets?fields=name%2Ctargeting&access_token=" + page_Token);
string getPostData = WebClient.DownloadString(post_url);
string getPostActivity = WebClient.DownloadString(post_like_url);
string getPageTarget = WebClient.DownloadString(page_tagret_url);
string getUserData = WebClient.DownloadString(user_url);
DataTable dtPostData = ConvertJsonToDatatableLinq(getPostData);
var userDataList = JsonConvert.DeserializeObject < FacebookJsonConversion.Root > (getUserData);
var pageActivity = JsonConvert.DeserializeObject < PostActivityJsonConversion.Root > (getPostActivity);
var pageTarget = JsonConvert.DeserializeObject < PageTargetJsonConversion.Root > (getPageTarget);
List < object > postData = new List < object > ();
postData.Add(dtPostData);
postData.Add(pageActivity);
postData.Add(pageTarget);
postData.Add(userDataList);
return View(postData);
}



ASP.NET MVC 6 Hosting - HostForLIFEASP.NET :: Exception Filters in MVC

clock July 16, 2021 08:10 by author Peter

Exceptions are part and parcel of an application. They are a boon and a ban for an application too. Isn't it? This would be controversial, for developers it helps them track minor and major defects in an application and sometimes they are frustrating when it lets users land on the Yellow screen of death each time. This would make the users mundane to the application. Thus to avoid this, developers handle the exceptions. But still sometimes there are a few unhandled exceptions.


Now what is to be done for them? MVC provides us with built-in "Exception Filters" about which we will explain here.

Let's start!
 
A Yellow screen of Death can be said is as a wardrobe malfunction of our application.
 
Get Started
Exception filters run when some of the exceptions are unhandled and thrown from an invoked action. The reason for the exception can be anything and so is the source of the exception.
 
Creating an Exception Filter
Custom Exception Filters must implement the builtin IExceptionFilter interface. The interface looks as in the following:
    public interface IExceptionFilter
    {  
       void OnException(ExceptionContext filterContext)  
    }  


Whenever an unhandled exception is encountered, the OnException method gets invoked. The parameter as we can see, ExceptionContext is derived from the ControllerContext and has a number of built-in properties that can be used to get the information about the request causing the exception. Their property's ExceptionContext passess are shown in the following table: 

Name Type Detail
Result ActionResult The result returned by the action being invoked.
Exception Exception The unhandled exceptions caused from the actions in the applications.
ExceptionHandled BOOL This is a very handy property that returns a bool value (true/false) based on if the exception is handled by any of the filters in the applicaiton or not.

The exception being thrown from the action is detailed by the Exception property and once handled (if), then the property ExceptionHandled can be toggled, so that the other filters would know if the exception has been already handled and cancel the other filter requests to handle. The problem is that if the exceptions are not handled, then the default MVC behavior shows the dreaded yellow screen of death. To the users, that makes a very impression on the users and more importantly, it exposes the application's handy and secure information to the outside world that may have hackers and then the application gets into the road to hell. Thus, the exceptions need to be dealt with very carefully. Let's show one small custom exception filter. This filter can be stored inside the Filters folder in the web project of the solution. Let's add a file/class called CustomExceptionFilter.cs.
    public class CustomExceptionFilter: FilterAttribute,  
    IExceptionFilter   
    {  
        public void OnException(ExceptionContext filterContext)   
        {  
            if (!filterContext.ExceptionHandled && filterContext.Exception is NullReferenceException)   
            {  
                filterContext.Result = new RedirectResult("customErrorPage.html");  
                filterContext.ExceptionHandled = true;  
            }  
        }  
    }  

Now let us understand what this actually does. As we can see, this implements the interface as said earlier and thus implements the method, OnException. This method has the parameter ExceptionContext, the properties of which is specified in the table. In this custom filter we have handled the most common and neglected exception "Null Reference Exception" that arises when a value returning null is not handled/checked and used in further implementations. The custom filter derives the FilterAttribute so as to be used as an Attribute over the action or the controller directly like [CustomExceptionFilter]. In this implementation above, we have used nearly all the important properties of the ExceptionContext. First, the check is used for the ExceptionHandled that returns a Boolean value if the exception has been handled or not. If not then Check for the type of exception that has arisen.
 
Since here we have used the NullReferenceException, we check for that exception. Then if the conditions are satisfied/passed we manipulate the result and return the RedirectResult (ActionResult type) and let the users land on a custom error page created in the application, to avoid the yellow dreaded screen. The use of the filter is pretty simple since this custom filter extends from the FilterAttribute. So based on the usage, this can be used as [CustomExceptionFilter] on the Controller Level or the individual Action level, whichever is relevant.
    //Over controller  
    [CustomExceptionFilter]  
    public class HomeController:Controller
    {  
       //......  
    }
    //Over the Action  
    [CustomExceptionFilter]  
    public ActionResult Index()
    {  
       //.......  
    }  


Now, let's explain the builtin HandleAttribute. This is a built-in class used in a similar way as a filter attribute in MVC applications. The most important thing is this attribute works only when the custom errors in the web.config is enabled or set to true.
 
The default mode for this element is RemoteOnly that will only work out when the application is deployed and the request is made from some other systems. Let's look at the properties of the HandleError Attribute.

    ExceptionType: This property, as the name suggests, indictes the attribute of the type of exception it needs to handle.

    View: This is the property that we need to specify to let the attribute land the end users after handling the exception.

    Master: If we have a special layout for the error page then this master can be set to that layout path. If left empty, this will take the default layout of the application for the error pages.

Thus, the following code snippet shows how to use the HandleError attribute.
    [HandleError(ExceptionType = typeof(NullReferenceException), View = "CustomErrorPage")]
    {  
       public Action Result
       {  
          //........  
          var testVal = null;  
          //Unhandled and used..  
       }
    }

Caution
While reading through the Adam Freeman, a very interesting note of caution was said for when using the HandleError attribute. In the custom error page, we would be using the HandleError Info like the Stack Trace, the exception message and so on. Since we would not like to show this to the end user, we need to put the stack trace inside a hidden field or make the HTML tag invisible because The view is not displayed to the user unless the Exception.StackTrace is included in the View.
 
Thus, we learned the creation of custom exception filters as well as the built-in filters in MVC applications. There are various ways/tools now to handle exceptions, but still we can make use of these filters to avoid detrimental effects on our applications.
 
I hope this would help developers and beginners. The concept is interesting when we use them. So start using and enjoy coding.



ASP.NET MVC 6 Hosting - HostForLIFEASP.NET :: Binding Dropdownlist With Database In MVC

clock July 8, 2021 07:36 by author Peter

This article shows how to bind a dropdownlist in various ways with a database.
I know you have seen many articles regarding dropdownlist but no one is showing binding with a database.


I saw most developers coming from webform development and not find it easy to use this HTML control. There are server controls in ASP.NET webforms that are easy to bind.

And in the same way in an Edit Form this shows how to dropdownlist selected.

I am using dapper to access the data from the database. Please do not be shocked, its an ORM and easy to use compared to Entity Framework.

But it is the same as Entity Framework. Do not worry, in the same way you can use this in Entity Framework.

Various ways to do the binding
    Using @html.DropDownList Model
    @Html.DropDownList("Mobiledropdown1", Model.MobileList)


Using @html.DropDownList with Viewbag
@Html.DropDownList("Mobiledropdown2", ViewBag.VBMobileList as SelectList)

Using @html.DropDownListFor With Model

@Html.DropDownListFor(M => M.MobileList, new SelectList(Model.MobileList,"Value", "Text"))

Using @html.DropDownList With hardcode values on View / with ViewBag.
1.​​​​ @Html.DropDownList("Mobiledropdown3", new List<SelectListItem>
     { new SelectListItem { Text = "HTC DESIRE", Value = "1", Selected=true},
       new SelectListItem { Text = "Moto G", Value = "2"},
       new SelectListItem { Text = "GO mobiles", Value = "3"}
       }, "Select Mobile")

2. @Html.DropDownList("Dr",ViewData["MyhardcodeValue"] as List<SelectListItem>)


Here is a table snapshot . I am also providing to you the table script in an attachment.
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Mobiledata](
    [MobileID] [int] IDENTITY(1,1) NOT NULL,
    [MobileName] [varchar](50) NULL,
    [MobileIMEno] [varchar](16) NULL,
    [MobileManufactured] [varchar](50) NULL,
    [Mobileprice] [decimal](18, 0) NULL,
 CONSTRAINT [PK_Mobiledata] PRIMARY KEY CLUSTERED
(
    [MobileID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

Let's start by creating the Model first.

I am adding the model with the name Mobiledata.

Adding all the fields that are present in the SQL Table and SelectList to get the data in the Collection.

[Table("Mobiledata")]
public class Mobiledata
{
    [Key]
    public int MobileID { get; set; }
    public string MobileName { get; set; }
    public string MobileIMEno { get; set; }
    public string MobileManufactured { get; set; }
    public Nullable<decimal> Mobileprice { get; set; }
    [NotMapped]
    public SelectList MobileList { get; set; }

}


For a Dapper User I am adding another class with the name MobileContext.
public class MobileContext
{
    SqlConnection con = new   SqlConnection(ConfigurationManager.ConnectionStrings["MYConnector"].ToString());
    public IEnumerable<Mobiledata> GetMobileList()
    {
        string query = "SELECT [MobileID],[MobileName]FROM [MobileDB].[dbo].[Mobiledata]";
        var result = con.Query<Mobiledata>(query);
        return result;
    }
}


This class will return an Enumerable list of MobileData.
We are complete with the Model part. I will now show you the Controller part.
I am adding the Controller with the name MobileDisplayController.

 

After adding the Controller you will see a similar view.
I have also added a Mobilecontext class; you can view it here.

MobileDisplayController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BindingDropdownListandSavingIT.Models;

namespace BindingDropdownListandSavingIT.Controllers
{
    public class MoblieDisplayController : Controller
    {
        MobileContext MCon = new MobileContext();

        public ActionResult Index()
        {
            return View(MD);
        }
    }
}

After adding the Controller now the main purpose is to pass a value to the view from the Controller.

Let's pass values.

MobileContext MCon = new MobileContext();
The following is the MobileContext class for getting the Enumerable List .

Mobiledata MD = new Mobiledata();

Mobiledata is the model that I am passing to the View.
In that Model you can see MobileList that is Enumerable.

MD.MobileList = new SelectList(MCon.GetMobileList(), "MobileID", "MobileName");

Now to that MobileList I am passing SelectList with Enumerable List from MobileContext Class and also value and Text that I want to display.

First way to Binding Dropdownlist.

MobileDisplayController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BindingDropdownListandSavingIT.Models;

namespace BindingDropdownListandSavingIT.Controllers
{
    public class MoblieDisplayController : Controller
    {
        MobileContext MCon = new MobileContext();

        public ActionResult Index()
        {
            Mobiledata MD = new Mobiledata();
            MD.MobileList = new SelectList(MCon.GetMobileList(), "MobileID", "MobileName"); // model binding
            return View(MD);
        }
    }
}


After passing the data now to display it in the View.

For that add a View by right-clicking inside ActionResult and select AddView and provide its name as Index.

After adding the View add a Namespace to the Model as shown below.
@model BindingDropdownListandSavingIT.Models.Mobiledata
@{
    ViewBag.Title = "ALL DROPDOWNLIST FUN AND LEARN";
}

<h2>ALL DROPDOWNLIST FUN AND LEARN</h2


<tr>
    <td>
        <div>
            @Html.Label("Normal Dropdownlist Binding")
        </div>
    </td>
    <td>
        <div class="editor-label">
            @Html.Label("Select Mobile Name")
        </div>
    </td>
    <td>
        <div class="editor-field">
            @Html.DropDownList("Mobiledropdown1", Model.MobileList, "Select Mobile")
        </div>
    </td>
</tr>


Here we can directly access the MobileList from the Model.

Now just run the application and just check it.

It's done.

Second way to Bind Dropdownlist
Now in the second way we just need to pass the same list to the Viewbag.

As in the first way we have passed a value to the model now in the same way we would pass a list to the Viewbag.
<tr>
    <td>
        <div>
            @Html.Label("Dropdownlist Binding Using ViewBag")
        </div>
    </td>
    <td>
        <div class="editor-label">
            @Html.Label("Select Mobile Name")
        </div>
    </td>
    <td>
        <div class="editor-field">
            @Html.DropDownList("Mobiledropdown2", ViewBag.VBMobileList as SelectList, "Select Mobile")
        </div>
    </td>
</tr>

ViewBag.VBMobileList = new SelectList(MCon.GetMobileList(), "MobileID", "MobileName");
// Viewbag


For your reference you can run and check it.

Third way to Binding Dropdownlist
In the third way everything will be the same but the binding to the DropdownlistFor is different.

Using the same model that was used for the first way to do the binding .
MD.MobileList = new SelectList(MCon.GetMobileList(), "MobileID", "MobileName");


Here is a snapshot to show how to bind.
<tr>
    <td>
        <div>
            @Html.Label("Dropdownlist Binding Using Model (Lamda Expression)")
        </div>
    </td>
    <td>
        <div class="editor-label">
            @Html.Label("Select Mobile Name")
        </div>
    </td>
    <td>
        <div class="editor-field">
            @Html.DropDownListFor(M => M.MobileID, new SelectList(Model.MobileList, "Value", "Text"), "Select Mobile")
        </div>
    </td>
</tr>

JavaScript

For binding the dropdownlist we require a LINQ expression and IEnumreable list.

As you have seen if you are creating a view directly using the scafffloding technique then you can see a LINQ lamda expression.

For example. @Html.TextboxFor(m => m.MobileName)

Fourth way to Binding Dropdownlist

In the last way we can pass hardcoded values to the dropdownlist on the View only.

1. Directly View
<tr>
    <td>
        <div>
            @Html.Label("Dropdownlist Binding on View Directly")
        </div>
    </td>
    <td>
        <div class="editor-label">
            @Html.Label("Select Mobile Name")
        </div>
    </td>
    <td>
        <div class="editor-field">
            @Html.DropDownList("Mobiledropdown3", new List<SelectListItem>
                      {
                      new SelectListItem { Text = "HTC DESIRE", Value = "1"},
                      new SelectListItem { Text = "Moto G", Value = "2"},
                      new SelectListItem { Text = "GO mobiles", Value = "3"}
                      }, "Select Mobile")
        </div>
    </td>
</tr>


2. Binding directly using ViewBag
The same List<SelectListItem> that we pass in the view directly can also be sent from the Controller and bound directly using a ViewBag.
<tr>
    <td>
        <div>
            @Html.Label("Dropdownlist Binding using SelectListitem and Viewbag")
        </div>
    </td>
    <td>
        <div class="editor-label">
            @Html.Label("Select Mobile Name")
        </div>
    </td>
    <td>
        @Html.DropDownList("Dr", ViewData["MyhardcodeVal"] as List<SelectListItem>)
    </td>
</tr>


Now we completed the binding of the Dropdownlist.

Now you may have a question of how to read the Dropdownlist values.

You can read using a FromCollection or Model.

Here you need to create a Post Method .

If you want to read all the values of the dropdownlist or any HTML control then you will get in FormCollection.

Post method from MobileDisplayController:
[HttpPost]
public ActionResult Index(FormCollection objfrm, Mobiledata objMd)
{
    string mobile1 = objfrm["Mobiledropdown1"];
    string mobile2 = objfrm["Mobiledropdown2"];
    string mobile3 = objfrm["Mobiledropdown3"];
    return View(objMd);
}


How to set a selected value of Dropdownlist on EditPage

Here I am showing how to show a selected dropdownlist value on Edit Page because this small thing will take time when you are new to this kind of technology.

Get the method of the Edit page from MobileDisplayController.

Output after editing.

How to add a Select at the top of the selection list. Just add a String value at the end of the Dropdownlist.

<div class="editor-field">
   @Html.DropDownList("Mobiledropdown1", Model.MobileList, "Select Mobile")
</div>



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Entity Framework With .Net Core MVC

clock June 23, 2021 09:20 by author Peter

This article is about Entity Framework with .Net Core MVC, Code-First approach.  Entity Framework with .Net MVC, Code-First, they have a lot of similar features.  We try to emphasize the differences. 


At the end, we will have an .Net Core MVC app that can consume a database directly through entity framework.
 
Step 1 - Create an ASP.NET Core MVC app

 We use the current version of Visual Studio 2019 16.9.3 and .NET Core 5.0 to build the app:

    Start Visual Studio and select Create a new project.
    In the Create a new project dialog, select ASP.NET Core Web App (Model-View-Controller) > Next.
    In the Configure your new project dialog, enter MvcMovie for Project name > Next.
    In the Additional Information dialog, select .NET 5.0 in the target framework dropdowns > Create

Note
    For beginners, you may reference here.
    We use the same project name as article (1), to keep it consistent.

Build and run the app, you will see the following image shows the app,

Step 2: Add a Data Model
Add a data model, an entity class, into the app, with name as Movie:
    In Solution Explorer, right click the Models folder, > Add,
    In the Add New item dialog, Select Class, Enter the class name Movie > Add.
    Add the following five properties to the Movie class:

    using System;  
      
    namespace MvcMovie.Models  
    {  
        public class Movie  
        {  
            public int ID { get; set; }  
            public string Title { get; set; }  
            public DateTime ReleaseDate { get; set; }  
            public string Genre { get; set; }  
            public decimal Price { get; set; }  
        }  
    }

Step 3: Set up DbContext
Add another class for DbContext name as MvcMovieContext (Note: the content is different from one of MVC):
    using Microsoft.EntityFrameworkCore;  
      
    namespace MvcMovie.Models  
    {  
        public partial class MovieCoreDBContext : DbContext  
        {  
            public MovieCoreDBContext()  
            { }  
            public MovieCoreDBContext(DbContextOptions<MovieCoreDBContext> options)  
                : base(options)  
            { }  
            public virtual DbSet<Movie> Movies { get; set; }  
        }  
    }


In order to use Microsoft.EntityFrameworkCore, and the related class, you need to install it from NuGet Package Manager.
 
Step 4: Set up Data Connection
Add the Connection in the appsettings.json file

    {  
      "Logging": {  
        "LogLevel": {  
          "Default": "Information",  
          "Microsoft": "Warning",  
          "Microsoft.Hosting.Lifetime": "Information"  
        }  
      },  
      
      "ConnectionStrings": {  
        "MovieCoreConnection": "Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=aspnet-MvcMovie;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\\Movies.mdf",  
      },  
      
      "AllowedHosts": "*"  
    }

Register the database connection context into Class starup.cs inside ConfigureServices,
    public void ConfigureServices(IServiceCollection services)  
    {  
        services.AddDbContext<MovieCoreDBContext>(options =>  
                options.UseSqlServer(Configuration.GetConnectionString("MvcCoreMovieContext")));
        ......
    }


In order to use the middleware UseSqlServer,  you need to install Microsoft.EntityFrameworkCore.SqlServer from NuGet Package Manager.
 
Note

In .Net Framework MVC, you don't actually need to add connection string, Entity Framework will create a LocalDB database in the users directory with the fully qualified name of the DbContext class. However, in .Net Core, you have to add a connection string in the appsettings.json file and have to register it in Startup file.  Otherwise, it will not work.
 
And finally, you even have to Migrate and Update database before to make the database work, see the next step.
 
Step 4.5:  Migrate and Update database (not necessary for .Net Framework MVC)
 
We add the Step 4.5 here to do the extra job. Click "Tools->NuGet Package Manager->Package Manager Console", and run the PMC command (make them in one line),
    Add-Migration -Name initialMigration -Context MvcCoreMovieContext

Run PMC command,
    update-database

Note
her stuff from the Step 5 below will be the exactly same procedure as MVC module, we will just keep it for consistence.
 
Step 5:  Create Controller to access data from entity framework
From Visual Studio IDE,
    Right-click the Controllers folder.
    Select Add > New Scaffolded Item Or Controller to open the window Add New Scaffolded Item
    In the Add New Scaffold Item dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add.;
    In the Add Controller dialog box,
        Select Movie (MvcMovie.Models) for the Model class.
        Select MovieDBContext (MvcMovie.Models) for the Data context class.
        For the Controller name enter MoviesController.
        Click Add.

If you get an error, you probably didn't build the application before starting adding the controller.) Visual Studio creates the following files and folders:

    A MoviesController.cs file in the Controllers folder.
    A Views\Movies folder.
    Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the new Views\Movies folder

 Visual Studio automatically created the CRUD (create, read, update, and delete) action methods and views:


Note
We will not exame the code in details, if you wanted, you may go here.

Step 6: Run the App, and Test

For convenience, you can update one line code in file Views/Shared/_Layout.chtml
<body>  
<div class="navbar navbar-inverse navbar-fixed-top">  
    <div class="container">  
        <div class="navbar-header">  
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
                <span class="icon-bar"></span>  
                <span class="icon-bar"></span>  
                <span class="icon-bar"></span>  
            </button>  
            @Html.ActionLink("MVC Core Movie", "Index", "Movies", new { area = "" }, new { @class = "navbar-brand" })  
        </div>  
        <div class="navbar-collapse collapse">  
            <ul class="nav navbar-nav">  
                <li>@Html.ActionLink("Home", "Index", "Home")</li>  
                <li>@Html.ActionLink("About", "About", "Home")</li>  
                <li>@Html.ActionLink("Contact", "Contact", "Home")</li>  
            </ul>  
        </div>  
    </div>  
</div>  
......
</body>


Run the App, the final result will be:




ASP.NET MVC 6 Hosting - HostForLIFEASP.NET :: Output Caching in MVC

clock June 16, 2021 09:09 by author Peter

The main purpose of using Output Caching is to dramatically improve the performance of an ASP.NET MVC Application. It enables us to cache the content returned by any controller method so that the same content does not need to be generated each time the same controller method is invoked. Output Caching has huge advantages, such as it reduces server round trips, reduces database server round trips, reduces network traffic etc.

 
Keep the following in mind:
    Avoid caching contents that are unique per user.

    Avoid caching contents that are accessed rarely.

    Use caching for contents that are accessed frequently.

Let's take an example. My MVC application displays a list of database records on the view page so by default each time the user invokes the controller method to see records, the application loops through the entire process and executes the database query. And this can actually decrease the application performance. So, we can advantage of the "Output Caching" that avoids executing database queries each time the user invokes the controller method. Here the view page is retrieved from the cache instead of invoking the controller method and doing redundant work.
Cached Content Locations
 
In the above paragraph I said, in Output Caching the view page is retrieved from the cache, so where is the content cached/stored?
 
Please note, there is no guarantee that content will be cached for the amount of time that we specify. When memory resources become low, the cache starts evicting content automatically.
 
OutputCache label has a "Location" attribute and it is fully controllable. Its default value is "Any", however there are the following locations available; as of now, we can use any one.
 
1. Any   2. Client   3. Downstream   4. Server   5. None   6. ServerAndClient
 
With "Any", the output cache is stored on the server where the request was processed. The recommended store cache is always on the server very carefully. You will learn about some security related tips in the following "Don't use Output Cache".
 
How Output Cache Works
It is very important to understand how the "Output Cache" works. Anyone who invokes a controller method will get the same cached version of the view page. This means that the amount of work that the web server must perform to serve the view page is dramatically reduced.
 
For example, I have recorded a GIF here to show you how the same request is being made from three different clients (here three different browsers) and we are getting the same cached version (look at the time).

Okay, now let's look at the code, how I developed the one above, how to make any controller action or method cacheable. Here it is
[OutputCache(Duration = 10, VaryByParam = "name")]
 
Just add the preceding label before the controller method. The duration is in seconds, 10 seconds here. If you don't provide a "Duration" value then the default will be used, 60 seconds. I am using VaryByParam="name" and "VeryByParam" is something that makes many differences that you should care about that will be discussed later. "name" is a parameter passed by the user with the request to do database records filering.
 
Here is the complete code:
    [HttpPost]  
        [OutputCache(Duration = 10, VaryByParam = "name")]  
        public ActionResult SearchCustomer(string name = "")  
        {  
            NorthwindEntities db = new NorthwindEntities();  
            var model = from r in db.Customers  
                        where r.ContactName.Contains(name)  
                        select r;  
            if (model.Count() > 0)  
            {  
                return View(model);  
            }  
            else  
            {  
                return View();  
            }  
        }  


In the code above, I'm looking at the "name" parameter passed by the user and then, depending on the name, selecting matching records with a LINQ query and then checking if the model has the number of records greater than zero then send the model to the view else simply send the view (no model).
VaryByParam can be one of the following types:

1. VaryByParam = "none": Think of it like, we don't want to care about the form parameter or query string parameter passed by the user from the view page. If I use "none" then it will create the same cached version of the content for every user who visits the website, and the content will only change after a specified number of seconds (here 10 seconds).

Let's use [OutputCache(Duration = 10, VaryByParam = "none")] in the code above and look at the behavior.

In above GIF you can notice on second request to see list of records that contains "a" nothing happens, because it is displaying the cached data.
2. VaryByParam = "name": This property enables you to create different cached versions of the content when a form parameter or query string parameter varies. In other words if I find records matching "ce" string then a new cache will be created by replacing the older one, again if I find records matching "ab" string then a new cache will be created by replacing the last one ("ce" cached), no matter duration is elapsed or not.
 
Let's use [OutputCache(Duration = 10, VaryByParam = "name")] in code above and look at behavior.

In the above GIF note that on each new request with a different query string parameter or form parameter, a new cache is being created; look at the time it is changing. Here the use of the cache is that if I request the same thing that I requested previously then the cached version will be rendered, here it is:

In the above GIF note that nothing happens (look at the time) when I continuously request the same information, rendering the cached version.
3. VaryByParam = "*": We can use * for all parameters or a semi-colon separated list to cache various versions. This works very similar to the one above (VaryByParam="name").
    [OutputCache(Duration = 10, VaryByParam = "*")]  
    public ActionResult SearchCustomer(string name = "", string city = "")  
    {  
        NorthwindEntities db = new NorthwindEntities();  
        ...  

OR
    [OutputCache(Duration = 10, VaryByParam = "name; city")]  
    public ActionResult SearchCustomer(string name = "", string city = "")  
    {  
        NorthwindEntities db = new NorthwindEntities();  
        ...  

Both scenarios work the same, so use whichever one that makes you happy.
Check Web Page is Cache-able or not?
 
Fiddler is a great tool if you want to check whether a requested web page is cache-able or not, here is a GIF image of it.

In the above GIF you can see the GET request is not cacheable whereas the POST request is cacheable and with max-age: 10 seconds.
Don't use Output Cache
 
Here you will learn about some quick security related issues and their prevention.

Danger 1
We should always be careful while using "OutputCache", I will show you an example here. Let's look at the following controller action method and try finding security vulnerabilities.
    [OutputCache(Duration = 10, VaryByParam = "none")]  
        public ActionResult Profiles()  
        {  
            if (User.Identity.IsAuthenticated)  
            {  
                MembershipUser u = Membership.GetUser(User.Identity.Name);  
                ViewBag.welcomeNote = "Welcome back " + User.Identity.Name + ". Your last login date was " + u.LastLoginDate;  
            }  
            else  
            {  
                ViewBag.welcomeNote = "Welcome Guest";  
            }  
            return View();  
        }  
       


Now, I'm running the code above, see how the usernames are appearing in both (IE and Chrome) browsers, the GIF is given below. Username is also being cached and stored on the server for other users.

In the above controller action method we don't have a "VaryByCustom" or "Location" attribute with "OutputCache" to safeguard it, so by default it uses Location = OutputCacheLocation.Any that is dangerous in this case. If you are using membership in the web application then you should pay special attention. A few ways are given below, the first is more secure and recommendable.

1st Way
You can also take advantage of the VaryByCustom property in [OutputCache] by overriding HttpApplication.GetVaryByCustomString and checking HttpContext.Current.User.IsAuthenticated.

This is what I will create in the Global.asax.cs file:
    public override string GetVaryByCustomString(HttpContext context, string custom)  
    {  
        if (custom == "LoggedUserName")  
        {  
            if (context.Request.IsAuthenticated)  
            {  
                return context.User.Identity.Name;  
            }  
            return null;  
        }  
        return base.GetVaryByCustomString(context, custom);  
    }  


And then use it in the OutputCache attribute:
    [OutputCache(Duration = 10, VaryByParam = "none", VaryByCustom = "LoggedUserName")]  
    public ActionResult Profiles()  
    {  
        //...  
    }  

Now for every user logged in on the website OutputCache will create a separate version, and it works great. We can even use Duration, VaryByParam, VaryByCustom and Location attributes together to make it more productive, useful and secure.

We can also enable separate cache entries for each browser, VaryByCustom can be set to a value of "browser". This functionality is built into the caching module, and will insert separate cached versions of the page for each browser name and major version. You don't need to override HttpApplication.GetVaryByCustomString.
    [OutputCache(Duration = 10, VaryByParam = "none", VaryByCustom = "browser")]  
    public ActionResult Profiles()  
    {  
       ...  


2nd Way
See, this is less reliable but works. You should use Location = OutputCacheLocation.Client. If you don't, the login username will also be cached and stored on the server for other users and that is confusing & quite dangerous.

Here is the complete controller action method code.
    [OutputCache(Duration = 10, VaryByParam = "none", Location = OutputCacheLocation.Client)]  
    public ActionResult Profiles()  
    {  
        ...  
    }  

Note 1: POST requests are not cached on the client, in other words this will not work because it is a POST request and the caching location is on the client.
      [HttpPost]  
    [OutputCache(Duration = 10, VaryByParam = "name", Location = OutputCacheLocation.Client)]  
    public ActionResult SearchCustomer(string name = "")  
    {  
        ...  
    }  


Note 2: If you are trying to test client-side caching (like the one given above) and hitting F5 then you are losing the client cache. The way the client cache is supposed to work is that you have links on the site pointing to the Client action from some other views and when the user clicks on those links the cached version will be served.

Danger 2
If you want a more secure application then you should only enable caching for a page when the page does not require authorization. Normally, you require authorization for a page when you display personalized data in the page. Since you don't want personalized data to be shared among multiple users, don't cache pages that require authorization.
    [Authorize]  
    [OutputCache(Duration = 10, VaryByParam = "none")]  
    public ActionResult CreditCardDetails()  
    {  
        ...  
    }  


In the code above, you are combining OutputCaching and Authorize with an action method that contains your credit card information. And you know how OutputCaching stores data out of the database that is not as secure as a database. So you are broadcasting your private information to the entire world. Don't do it.

Creating Cache Profile
It is very difficult to change the rules (like Duration, VaryByParam, VaryByCustom, Location) used with "OutputCache" on each controller method when your large application has already been deployed.

So, there is an alternative to configure the OutputCache profile in the web.config file. By configuring output caching in the web configuration file, you can control it on one central location. You can create one cache profile and apply the profile to several controllers or controller actions. Also, you can modify the web configuration file without recompiling your application. Any changes to the web configuration file will be detected automatically and applied to the entire application.

In the following code you can see I have used a new attribute CacheProfile that maps to Cache10Seconds that is in web.config.
    [OutputCache(CacheProfile = "Cache10Seconds", VaryByCustom = "LoggedUserName")]  
    public ActionResult Profiles()  
    {  
       ...  

And then web.config:
    <system.web>  
      <caching>  
        <outputCacheSettings>  
            <outputCacheProfiles>  
                <add name="Cache10Seconds" duration="10" varyByParam="none"/>  
            </outputCacheProfiles>  
        </outputCacheSettings>  
      </caching>  
      ...  


Please note, I moved Duration, VaryByParam and Location (we can use it also) in web.config but not VaryByCustom and the reason is, it is used for overriding the rules.
Now, assume for any reason I want to disable caching for an entire application that has already been deployed to production, then you can simply modify the cache profiles defined in the web configuration file.
 
We can even disable it as in the following:

    <system.web>  
        <caching>  
            <outputCache enableOutputCache="false" =""/>  
            <outputCacheSettings>  
                  <outputCacheProfiles>  
                        <add name="Cache10Seconds" duration="10" varyByParam="none"/>                 
          </outputCacheProfiles>           
        </outputCacheSettings>  
      </caching>  

This approach is pretty good because rather than targeting any specific outputCacheProfile we can disable all at once, awesome.



ASP.NET MVC 6 Hosting - HostForLIFEASP.NET :: JsonResult Type in MVC

clock June 8, 2021 07:20 by author Peter

The JSON format is an open standard format. The format of data looks very easy to understand and the data objects consist of attribute-value pairs.

 
ContentEncoding: It helps to indicate the content encoding type, the default encoding for JSON is UTF-8.
ContentType: It helps to indicate the content type. The default content type for JSON is application/json; charset=utf-8.
Note: ContentType and ContentEncoding are not necessary to mention when sending the data in JSON format as the HTTP headers are having a responsibility to tell the recipient what kind of content they're dealing with.
Data: This indicates what the content data is, that means what you will send in JSON format.
JsonRequestBehavior: This property has two options. Those are AllowGet and DenyGet. The default option is DenyGet. When you send data in JSON format, using Get Request, it's necessary to specify the property as AllowGet otherwise it shows the error as “The request would be blocked since the JSON data is considered as sensitive data information”.
MaxJsonLength: This helps to get or set the maximum JSON content length that you will send. The default value for this is 2097152 characters, that is equal to 4 MB of Unicode string data. You can even increase the size based if needed, for that you will get an idea later in this article.
RecursionLimit: Indicates the constraining number of object levels to process. The default value is 100. It means you can serialize the objects that are nested to a depth of 100 objects referencing each other. In a general scenario, the default limit 100 is obviously sufficient when you deal with a JsonResult so there is no need to increase it even though you have the option to increase the limit if required.

Sample Project with Various Scenarios by using JsonResult
Create a new project with the name JsonResultDemo and choose the template as MVC as shown in the following screenshots.

Now, click on the OK button then the displayed screen is as in the following.

As in the preceding template, you need to select the “Add Unit Tests” option as well. So It helps to create a Unit Test project and then again click on the OK button then the project will be created and the startup application page displayed like the following.

Now, add a controller and provide the name as “JsonDemoController” as in the following.

Click on the Controller and then it will open the popup window as in the following.

Now, click on the “Add” button and then it opens a popup to enter the name. So enter the name as “JsonDemoController” as shown in the screenshot.

After adding the controller to the project the controller page looks like the following.

Until now, you are done with the creation of the sample project template with the addition of one controller named “JsonDemoController”.
 
Scenario 1: Send JSON Content welcome note based on user type
 
In this scenario, you will learn how to send a simple welcome note message in JSON format from the controller. Now, replace the existing code with the following code in the JsonDemoController.cs file.
    using System;  
    using System.Collections.Generic;  
    using System.Text;  
    using System.Web.Mvc;  
    using System.Web.Script.Serialization;  
    using JsonResultDemo.Models;  
      
    namespace JsonResultDemo.Controllers  
    {  
        public class JsonDemoController : Controller  
        {  
            #region ActionControllers  
      
            /// <summary>  
            /// Welcome Note Message  
            /// </summary>  
            /// <returns>In a Json Format</returns>  
            public JsonResult WelcomeNote()  
            {  
                bool isAdmin = false;  
                //TODO: Check the user if it is admin or normal user, (true-Admin, false- Normal user)  
                string output = isAdmin ? "Welcome to the Admin User" : "Welcome to the User";  
      
                return Json(output, JsonRequestBehavior.AllowGet);  
            }  
         }  
    }


Then, build the application (F6) and then hit the F5 to run an application and then navigate to the following URL http://localhost:49568/JsonDemo/WelcomeNote (It might be a chance to get a different Port Id at your end).

Then the displayed screen looks like the following.

In this scenario, you now have an idea of how to send a simple string in JSON format.
 
Scenario 2: Get the list of users in JSON Format
In this scenario, you will send a list of users in JSON format.
 
Step 1: Add a class file “UserModel.cs” like the following.

Click on “Class” and then the displayed link is as the following.

Enter the name as “UserModel.cs” and then click on the Add button.
 
Step 2: Update the code in UserMode.cs with the following code.
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
      
    namespace JsonResultDemo.Models  
    {  
        public class UserModel  
        {  
            public int UserId { get; set; }  
            public string UserName { get; set; }  
            public string Company { get; set; }  
        }  
    }

Step 3: Add one method named GetUsers in the JsonDemoController.cs file that will return the list of sample users.
            /// <summary>  
            /// Get the Users  
            /// </summary>  
            /// <returns></returns>  
            private List<UserModel> GetUsers()  
            {  
                var usersList = new List<UserModel>  
                {  
                    new UserModel  
                    {  
                        UserId = 1,  
                        UserName = "Ram",  
                        Company = "Mindfire Solutions"  
                    },  
                    new UserModel  
                    {  
                        UserId = 1,  
                        UserName = "chand",  
                        Company = "Mindfire Solutions"  
                    },  
                    new UserModel  
                    {  
                        UserId = 1,  
                        UserName = "Abc",  
                        Company = "Abc Solutions"  
                    }  
                };  
      
                return usersList;  
            }

Step 4: Create one Action Controller method named GetUsersData with the following code in the JsonDemoController.cs file.
    /// <summary>  
            /// Get tthe Users data in Json Format  
            /// </summary>  
            /// <returns></returns>  
            public JsonResult GetUsersData()  
            {  
                var users = GetUsers();  
                return Json(users, JsonRequestBehavior.AllowGet);  
            }


Step 5: Run the application with this URL http://localhost:49568/JsonDemo/GetUsersData then the output looks like the following.
 

Scenario 3: Create JSON data at the client side and send content to the controller
 
In this scenario, you will create JSON data at the client side and then that data will be sent to the Controller action. The controller action request type is HttpPost.
 
Step 1: Create one Action controller method named Sample like the following in the JsonDemoController.cs file.

    /// <summary>  
    /// Sample View  
    /// </summary>  
    /// <returns></returns>  
    public ActionResult Sample()  
    {  
        return View();  
    }


Step 2: Create a View file named “Sample.cshtml” by right-clicking on View() in the Sample action controller method then click on “Add View” in the Sample action like the following.

By clicking on Add View it opens a popup and deselects the "Use a layout page" option. It then should look as in the following.

Now, click on the OK button then the sample.cshtml file will be created.
 
Step 3: Replace it with the following cshtml code in the sample.cshtml file.

    @{  
        Layout = null;  
    }  
      
    <!DOCTYPE html>  
      
    <html>  
        <head>  
            <meta name="viewport" content="width=device-width" />  
            <title>Create Sample JSON Data and send it to controller</title>  
        </head>  
        <body>  
            <div>  
                <label>Create Sample User JSON Data and send it to controller</label><br/><br />  
                <input type="button" id="btnUpdateUserDetail" value="Update User Detail" onclick="UpdateUserDetail();"/>  
            </div>  
        </body>  
    </html>  
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
    <script lang="en" type="text/javascript">  
        function UpdateUserDetail() {  
            var usersJson = GetSampleUsersList();  
            var getReportColumnsParams = {  
                "usersJson": usersJson  
            };  
            $.ajax({  
                type: "POST",  
                traditional: true,  
                async: false,  
                cache: false,  
                url: '/JsonDemo/UpdateUsersDetail',  
                context: document.body,  
                data: getReportColumnsParams,  
                success: function (result) {  
                    alert(result);  
                },  
                error: function (xhr) {  
                    //debugger;  
                    console.log(xhr.responseText);  
                    alert("Error has occurred..");  
                }  
            });  
        }  
        function GetSampleUsersList() {  
            var userDetails = {};  
            var usersList = [];  
            for (var i = 1; i <= 3; i++) {  
                userDetails["UserId"] = i;  
                userDetails["UserName"] = "User- " + i;  
                userDetails["Company"] = "Company- " + i;  
                usersList.push(userDetails);  
            }  
            return JSON.stringify(usersList);  
        }  
    </script>


The following is a brief description of the Sample.cshtml file:
    The HTML body contains a label, about, to describe the functionality and one input button with an onclick of the UpdateUserDetail() function.

    The JavaScript part contains the jQuery reference and it contains two functions.

    GetSampleUsersList() will return the sample users in a stringified JSON format.

    UpdateUserDetail() sends the ajax request of post type for JsonDemoController with UpdateUserDetail action.

Step 4: A Create Action method named UpdateUsersDetail in the JsonDemoController as in the following and put a breakpoint in this method on the first line of code to help to trace the details.
    /// <summary>  
    /// Update the user details  
    /// </summary>  
    /// <param name="usersJson">users list in JSON Format</param>  
    /// <returns></returns>  
    [HttpPost]  
    public JsonResult UpdateUsersDetail(string usersJson)  
    {  
        var js = new JavaScriptSerializer();  
        UserModel[] user = js.Deserialize<UserModel[]>(usersJson);  
      
        //TODO: user now contains the details, you can do required operations  
        return Json("User Details are updated");  
    }


Step 5: Build and run the application (hit F5) with the URL (http://localhost:49568/JsonDemo/Sample) then the resultant screen looks like the following.

Step 6: Now, click on the “Update User Detail” button as it appears in the aforesaid screenshot. Then the resultant screen looks like the following.

Step 7: Just review the preceding image, you can identify that you are able to send the JSON data to the controller action from the client side and as well as you have deserialized the JSON data and assigned that data to the UserModel entity.
 
Scenario 4: How to handle a huge amount of JSON Data
 
In this scenario, you will get an idea of how to send a huge amount of JSON Data. Actually, in certain scenarios, you must send a huge amount of data from a controller to a view. In that case, the following example will be helpful to you.
 
Step 1: Create one method named GetUsersHugeData() as in the following. It just helps to generate sample user data.  
            /// <summary>  
            /// Get the huge list of users  
            /// </summary>  
            /// <returns></returns>  
            private List<UserModel> GetUsersHugeData()  
            {  
                var usersList = new List<UserModel>();  
                UserModel user;  
                for (int i = 1; i < 51000; i++)  
                {  
                    user = new UserModel  
                    {  
                        UserId = i,  
                        UserName = "User-"+i,  
                        Company = "Company-"+i  
                    };  
                    usersList.Add(user);  
                }  
      
                return usersList;  
            }

Step 2: Create an Action method named GetUsersHugeList() like the following in the JsonDemoController.cs file.
    /// <summary>  
    /// Get the huge list of Users  
    /// </summary>  
    /// <returns></returns>  
    public JsonResult GetUsersHugeList()  
    {  
        var users = GetUsersHugeData();  
        return Json(users, JsonRequestBehavior.AllowGet);  
    }


Step 3: Now, build and run (hit F5) the application with the URL (http://localhost:49568/JsonDemo/GetUsersHugeList) then the error screen appears like the following.

Step 4: To fix the preceding error add the following code in the JsonDemoController file. This methods helps to update the MaxJsonLength property value to Int32.MaxValue.
     /// <summary>  
    /// Override the JSON Result with Max integer JSON lenght  
    /// </summary>  
    /// <param name="data">Data</param>  
    /// <param name="contentType">Content Type</param>  
    /// <param name="contentEncoding">Content Encoding</param>  
    /// <param name="behavior">Behavior</param>  
    /// <returns>As JsonResult</returns>  
    protected override JsonResult Json(object data, string contentType,  
        Encoding contentEncoding, JsonRequestBehavior behavior)  
    {  
        return new JsonResult()  
        {  
            Data = data,  
            ContentType = contentType,  
            ContentEncoding = contentEncoding,  
            JsonRequestBehavior = behavior,  
            MaxJsonLength = Int32.MaxValue  
        };  
    }


In the same way, you can increase the RecursionLimit property value. Also if you require JsonData with a depth (nested levels) greater than 100.
 
Step 5: Now, build and run (hit F5) the application with the URL (http://localhost:49568/JsonDemo/GetUsersHugeList) and then the huge data result appears instead of an error.

I have provided the formatted complete code for the JsonDemoController.cs file for what you have done until now in the aforesaid scenarios.
    using System;  
    using System.Collections.Generic;  
    using System.Text;  
    using System.Web.Mvc;  
    using System.Web.Script.Serialization;  
    using JsonResultDemo.Models;  
      
    namespace JsonResultDemo.Controllers  
    {  
        public class JsonDemoController : Controller  
        {  
            #region ActionControllers  
      
            /// <summary>  
            /// Welcome Note Message  
            /// </summary>  
            /// <returns>In a JSON Format</returns>  
            public JsonResult WelcomeNote()  
            {  
                bool isAdmin = false;  
                //TODO: Check the user if it is admin or normal user, (true-Admin, false- Normal user)  
                string output = isAdmin ? "Welcome to the Admin User" : "Welcome to the User";  
      
                return Json(output, JsonRequestBehavior.AllowGet);  
            }  
      
            /// <summary>  
            /// Get tthe Users data in JSON Format  
            /// </summary>  
            /// <returns></returns>  
            public JsonResult GetUsersData()  
            {  
                var users = GetUsers();  
                return Json(users, JsonRequestBehavior.AllowGet);  
            }  
      
            /// <summary>  
            /// Sample View  
            /// </summary>  
            /// <returns></returns>  
            public ActionResult Sample()  
            {  
                return View();  
            }  
      
            /// <summary>  
            /// Update the user details  
            /// </summary>  
            /// <param name="usersJson">users list in JSON Format</param>  
            /// <returns></returns>  
            [HttpPost]  
            public JsonResult UpdateUsersDetail(string usersJson)  
            {  
                var js = new JavaScriptSerializer();  
                UserModel[] user = js.Deserialize<UserModel[]>(usersJson);  
      
                //TODO: user now contains the details, you can do required operations  
                return Json("User Details are updated");  
            }  
              
            /// <summary>  
            /// Get the huge list of Users  
            /// </summary>  
            /// <returns></returns>  
            public JsonResult GetUsersHugeList()  
            {  
                var users = GetUsersHugeData();  
                return Json(users, JsonRequestBehavior.AllowGet);  
            }  
     
            #endregion  
     
     
            #region Methods  
      
            /// <summary>  
            /// Get the Users  
            /// </summary>  
            /// <returns></returns>  
            private List<UserModel> GetUsers()  
            {  
                var usersList = new List<UserModel>  
                {  
                    new UserModel  
                    {  
                        UserId = 1,  
                        UserName = "Ram",  
                        Company = "Mindfire Solutions"  
                    },  
                    new UserModel  
                    {  
                        UserId = 1,  
                        UserName = "chand",  
                        Company = "Mindfire Solutions"  
                    },  
                    new UserModel  
                    {  
                        UserId = 1,  
                        UserName = "Abc",  
                        Company = "Abc Solutions"  
                    }  
                };  
      
                return usersList;  
            }  
      
            /// <summary>  
            /// Get the huge list of users  
            /// </summary>  
            /// <returns></returns>  
            private List<UserModel> GetUsersHugeData()  
            {  
                var usersList = new List<UserModel>();  
                UserModel user;  
                for (int i = 1; i < 51000; i++)  
                {  
                    user = new UserModel  
                    {  
                        UserId = i,  
                        UserName = "User-"+i,  
                        Company = "Company-"+i  
                    };  
                    usersList.Add(user);  
                }  
      
                return usersList;  
            }  
      
            /// <summary>  
            /// Override the Json Result with Max integer JSON lenght  
            /// </summary>  
            /// <param name="data">Data</param>  
            /// <param name="contentType">Content Type</param>  
            /// <param name="contentEncoding">Content Encoding</param>  
            /// <param name="behavior">Behavior</param>  
            /// <returns>As JsonResult</returns>  
            protected override JsonResult Json(object data, string contentType,  
                Encoding contentEncoding, JsonRequestBehavior behavior)  
            {  
                return new JsonResult()  
                {  
                    Data = data,  
                    ContentType = contentType,  
                    ContentEncoding = contentEncoding,  
                    JsonRequestBehavior = behavior,  
                    MaxJsonLength = Int32.MaxValue  
                };  
            }  
     
            #endregion  
        }  
    }


You now have an idea of how to use a JsonResult type in MVC application with various scenarios. Now, it's time to test the controller action methods using the JsonDemoController.Test project.

Unit Testing the JsonResult in MVC
The main feature of MVC applications is it supports the Test Data Driven (TDD) approach. Since the Controller file is just a kind of class file, it's easy to implement the Test methods in the Test Project. Now you will learn how to test the JsonResult methods in the test project.
 
Step 1: Add a class file named “JsonDemoControllerTest.cs” to the JsonResultDemo.Tests projects like the following.



Click on “Class” to open a popup like the following and then update the name as “JsonDemoControllerTest.cs”.

Step 2: After clicking on the “Ok” button then the screen result looks like the following.

Step 3: Now, replace the existing code in the file JsonDeomControllerTest.cs with the following code.
    using System;  
    using System.Web.Mvc;  
    using Microsoft.VisualStudio.TestTools.UnitTesting;  
    using JsonResultDemo.Controllers;  
      
    namespace JsonResultDemo.Tests.Controllers  
    {  
        [TestClass]  
        public class JsonDemoControllerTest  
        {  
            [TestMethod]  
            public void WelcomeNote()  
            {  
                JsonDemoController controller = new JsonDemoController();  
      
                JsonResult result = controller.WelcomeNote();  
                string msg = Convert.ToString(result.Data);  
                // Assert  
                Assert.AreEqual("Welcome to the User", msg);  
            }  
        }  
    }


Brief Note about TestMethod of WelcomeNote()
    Create an object for JsonDemoController.

    Save the result of JsonDemoController controller method “WelcomeNote” method result in the “result” parameter of the type JsonResult.

    The string “msg” is assigned with the value from the JSON Result (result.Data).

    In this step, you are checking the expected output with the actual output using the Assert method. In a similar way, the Assert Method provides other options like AreNotEqual, AreSame, IsNotNull and so on.

Step 4: Right-click on the WelcomeNote method and click on “Run Unit Tests” then the screen result looks like the following.

Step 5: You can also do the “Run Tests” by the clicking of (Ctrl +R, T). Then you can view the results in Test Explorer like the following.

In a similar way, you can create more test methods and it will be helpful to check the functionality in various cases since it provides correct results or not. I hope this article gives you an idea of JsonResult, JsonResult Properties, the usage of JsonResult with various scenarios and how can you test the JsonResult using the Test Project.



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