Category Archives: MVC

How to use multiple model in view

If we have two model classes like Customer details and Employee detail. ASP.NET MVC allows you to pass only One model to a view. The view can be bound with one and only one model. From the above statement, we understood that either pass customer or employee details to the view. Then What if a view requires to display both models?. Let us we discuss the situation as follows:

How to overcome?

In MVC we cannot pass more than one models from a controller to the single view. To overcome this we can use ExpandoObject class.

What is ExpandoObject ?

The .NET 4.0 framework actually includes an ExpandoObject class which provides a dynamic object that allows us to add properties and methods on the fly.

  • ExpandoObject is a sealed type so we can’t use it as a base class
  • It doesn’t serialize to XML or DataContractSerializer/DataContractJsonSerializer

From msdn, Represents an object whose members can be dynamically added and removed at run time.

When to use ?

In some time we need to display more than one type of model data in to the single view. For example i am having two models namely CustomerDetails and EmployeeDetails and if i need to display both information in single view then we can use the ExpandoObject.

Example :

Model :

Creating simple model namelu CustomerDetail.cs and EmployeeDetail.cs as shown below.

CustomerDetail.cs

public class CustomerDetail
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string CustomerAdress { get; set; }
}

EmployeeDetail.cs

public class EmployeeDetail
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string EmployeeAdress { get; set; }
}

Controller :

public ActionResult Index()
{
dynamic detailModel = new ExpandoObject();
detailModel.EmployeeDetail = GetEmployeeDetail();
detailModel.CustomerDetail = GetcutomerDetail();
return View(detailModel);
}
private List<EmployeeDetail> GetEmployeeDetail()
{
List<EmployeeDetail> employeeDetail = new List<EmployeeDetail>();
employeeDetail.Add(new EmployeeDetail { EmployeeId = 1001, EmployeeName = "Aadharsh", EmployeeAdress = "xxxxxx" });
employeeDetail.Add(new EmployeeDetail { EmployeeId = 1002, EmployeeName = "GK", EmployeeAdress = "xxxxxx" });
return employeeDetail;
}
public List<CustomerDetail> GetcutomerDetail()
{
List<CustomerDetail> cutomerDetail = new List<CustomerDetail>();
cutomerDetail.Add(new CustomerDetail { CustomerId = 256, CustomerName = "Kavitha", CustomerAdress = "xxxxxx" });
cutomerDetail.Add(new CustomerDetail { CustomerId = 257, CustomerName = "Gnanam", CustomerAdress = "xxxxxx" });
return cutomerDetail;
}

View :

@using Multiple_Models_in_Single_View.Models;
@model dynamic
@{
ViewBag.Title = "Detail Page";
}
<div>============================</div>

<table>
<tr>
<th>Emp Id</th>
<th>Emp Name</th>
<th>Emp Adress</th>
</tr>
@foreach (EmployeeDetail employeeDetail in Model.EmployeeDetail)
{
<tr>
<td>@employeeDetail.EmployeeId</td>
<td>@employeeDetail.EmployeeName</td>
<td>@employeeDetail.EmployeeAdress</td>
</tr>
}
</table>
<div>============================</div>
<table>
<tr>
<th>Cus Id</th>
<th>Cus Name</th>
<th>Cus Adress</th>
</tr>
@foreach (CustomerDetail cutomerDetail in Model.CustomerDetail)
{
<tr>
<td>@cutomerDetail.CustomerId</td>
<td>@cutomerDetail.CustomerName</td>
<td>@cutomerDetail.CustomerAdress</td>
</tr>
}
</table>

OUTPUT

MultipleModel

How to map multiple urls to the same controller/Action

In this post we are going to discuss about how to map multiple URLs to the same controller/Action by the custom route.

Below example shows how write custom route

Custom code must be place inside the RouteConfig.cs.

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute( "MultipleUrls", "{phaseone,phasetwo}", new { controller = "home", action = "index", id = "" } );

routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}",defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
}
}

Explanation :

  •  MultipleUrls : Descripe the name of the route
  •  {phaseone,phasetwo} : controllers name with comma separator
  •  new { controller = “home”, action = “index”, id = “” } : It describe, where want to redirect for the above controllers

 OUTPUT :

Thanks to my friend manjunath for rise this question and make me find this solution

 

Action Result Return Type in MVC 4

ActionResult is a return type of a controller method in ASP.NET MVC. It help us to return models to views, other return value, and also redirect to another controller’s action method. There are many derived ActionResult types in MVC that we use to return the result of a controller method to the view.

What is ActionResult ?

  •  An ActionResult is a return type of a controller method in MVC.
  •  ActionResult are more specific for a particular view
  •  It is abstract class that has many subtypes

Types of ActionResult :

  • ViewResult
  • PartialViewResult
  • ContentResult
  • RedirectResult
  • RedirectToRouteResult
  • JsonResult
  • EmptyResult
  • FileResult
  • JavaScriptResult

Let we start discussion about types of ActionResult in one by one…

ViewResult :

  • It renders a specified view to the response stream.

 Example :

public ViewResult Index() {   return View(“sampleResult”); }

PartialViewResult:

  • Renders a specifed partial view to the response stream.

Example :

public PartialViewResult SamplePartialView()
{    return PartialView(“_LoadSamplePartial”); }

Note :

  • It will load the partial view to the main view

ContentResult :

  • It display the response stream without requiring a view .(like a plain text).

Example

public ActionResult About()
{
ViewBag.Message = “Your app description page.”;
return Content(“Sample Content Action”);
}

It simply write the string value in the page

RedirectResult :

  • It is used to perform an HTTP redirect to a given URL.

Example :

public ActionResult SampleRedirectResult()
{  return Redirect(“http://www.google.com/”); }

RedirectToRouteResult :

  • RedirectToResult is used to redirect by using the specified route values dictionary.

Example :

public ActionResult SampleRedirectToRouteResult()
{
return new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new
{
controller = “Sample”,
action = “SampleRedirectToRouteResultTest”,
Id = new int?()
}));
}

JsonResult :

  • Action methods return JsonResult (JavaScript Object Notation result) that can be used in ajax based application.

Example :

public ActionResult SampleJsonResult
{
… Logic here
return Json(sampleinfo);
}

EmptyResult : 

  • It return  NULL that is EmptyResult
  • return instance of EmptyResult class

Example :

return new EmptyResult();

FileResult :

  • Return a file from an action. (Pdf,Excel,image file,Html…)

Example :

public FileResult DownloadCustomerDetails()
{
//Parameters to file are
//1. The File Path on the File Server
//2. The content type MIME type
//3. Name of file To be save by Browser
string contentType = “application/pdf”;
string filepath = AppDomain.CurrentDomain.BaseDirectory + “/FileFolder/CustomerDetails.pdf”;
return File(filepath, contentType, “CustomerDetails.pdf”);

Output:

After calling the action method in browser , the file will ask for download as shown in below

http://localhost:52877/home/DownloadCustomerDetails

}

JavaScriptResult:

  • To improve clean separation of concerns by introducing the JavaScriptResult ActionResult.
  • Release notes says, “the JavaScriptResult class is used to execute JavaScript code that is created on the server and sent to the client.”

For Example,

Controller :

public JavaScriptResult SampleJavaScriptResult()
{
var s = “alert(‘Hi’)”;
return JavaScript(s);
}

View :

<script type=”text/javascript” src=”@Url.Content(“~/Home/SampleJavaScriptResult”)”></script>

Note :

The dynamic script file will be generated based on the action name (SampleJavaScriptResult)

Output:

After press F5, it will create the dynamic script file “SampleJavaScriptResult” which will append the content from action

Then it will display the alert message which was return from the action “SampleJavaScriptResult” as show in below

Creating Web API using MVC 4 with Razor

Here we will create simple Web API Application using MVC 4 with Razor

What is Web API?

From msdn, ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

When to use Web API?

  •    Web API when you want to create a resource based services over HTTP that can use the full features of HTTP    (like   URIs, request/response headers,various content formats).
  •   Use Web API when we want to expand service at wide way like mobile,browser,tablet…
  •   If we need a Web Service and without using SOAP, then ASP.Net Web API is best choice.

why we use Web API ?

WCF gives you the flexibility to use other protocols, but the REST implementation is a bit more complicated when compare to Web API

For Detail about REST , Go here

Example :

Step : 1

Create new project -> choose MVC Web Application and click ok

Step : 2

Next, in project template choose Web API and click ok


After creating Web API application we can see the same structure as MVC Application but in App_start, separate router file is created for Web API (that is WebApiConfig.cs) as shown below.

Step : 3

Open Values controller (which was created in default for Web API) ie., ValuesController


Here i made with simple changes like below ,

public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string

[] { “aadharsh”, “GnanamKavi” };
}
public string Get(int id)
{
if (id == 1){
return “Get value using id” +”–>”+ id;
}
if (id == 2){
return “Get value using id” + “–>” + id;
}
return null;
}
}

NOTE :

  •   In MVC Application controller implements Controller interface but in Web API controller implements      ApiController as base
  •   In web API controller, action methods are actually HTTP methods ie., GET,PUT…

Step :  4

Run the Application. When we run the Web API using below URL,

http://localhost:53934/api/Values :   The Web API route to Get() method (WebApiConfig.cs) as shown below, because there is no parameter append after the method (URL without parameter)

http://localhost:53934/api/Values/1 :  The Web API route to Get(int id) method (WebApiConfig.cs) as shown below, because there is a parameter append after the method (URL with parameter)

Note :

  • Web API is a light weight architecture and good for various device which have limited bandwidth like smart phones.
  • It also supports the MVC features such as routing, controllers, action, filter… this makes  us very simple and robust
  • Using Web API, we can get the resource in various format (like xml,json..)
  • let we see how to call PUT,DELETE methods with simple explanation

  First we want to include in web.config

<system.webServer><modules runAllManagedModulesForAllRequests=”true”></modules ></system.webServer>

then we can call using jquery (type : ‘PUT’/’DELETE’/’POST’/’GET’)

$.ajax({
url: ‘/api/Values/’ + truckId,
type: ‘PUT’,
contentType: “application/json; charset=utf-8”,
data: json,
success: function (results) {
}
});

How to create Unorderlist using HTML Helpers with custom Attribute

Creating Unorderlist using HTML Helpers with custom Attribute

Please refer to know how to use Extend HTML Helpers   here

.CS File

namespace CustomeHelpers
{
public static class CreatingUnorderedList
{
public static MvcHtmlString CreatingUnorderedListUsingAttribute(this HtmlHelper htmlHelper, string name, string value, string id)
{
var builder = new TagBuilder(“li”);
builder.Attributes

[“id”] = id;
builder.Attributes[“type”] = “radio”;
builder.Attributes[“name”] = name;
builder.Attributes[“value”] = value;
//creating Custom attribue in the Element
builder.Attributes[“listId”] = name + “-” + id;
if (id == “0”)
builder.SetInnerText(“Start List ” + id);
else if (id == “4”)
builder.SetInnerText(“End List ” + id);
else
builder.SetInnerText(“List ” + id);
return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}
}
}

Note : SetInnerText used for set the text/value for the element

View

<h2>Generating Unordered List using HTML Helpers</h2>
<ul>
@for (var loop_index = 0; loop_index < 5; loop_index++)
{
@Html.CreatingUnorderedListUsingAttribute(“custom_txtbox”, “Custom Helper Method”,loop_index.ToString())
}
</ul>

OUTPUT :



Below image shows  Unordered List with custom attribute listId in the li element

Server Side Model Validation in MVC 4 Razor

This article explains the ASP.NET MVC server-side validation using the Data Annotation classes. ASP.NET MVC Framework validates the data passed to the controller action and it populate ModelState with validation state based on the success/failure. Then the Model State passed object to the controller for the further process. Server side validations are play important role with sensitive information of a user.

Server Side Model Validation

  • Server side validations are required for ensuring that the received data is correct and in-valid.
  • If the received data is valid,then it will continue with further processing else show the Error message

Why we go for server-side Validation :

Some user may disable script in his browser, In this scenerio we must require to validate our data from dirty input values from the user. To avoid this we can use sever-side validation. we can validate a “MODEL”  in server-side by two ways:

  •     Model Validation with Data Annotations
  •     Explicit Model Validation

We already discussed about Model validation using Data Annotation here, so  let we discuss Explicit validation using simple registration form with user input.

Model :

public class UserRegistrationModel
{
public string UserName{get;set;}
public string Password{get;set;}
public string Address{get;set;}
public string MobileNo{get;set;}
public bool TermsAndCondtionAccepted{get;set;}
}

Controller :

public ActionResult Index(UserRegistrationModel mUserDetails)
{
if (Request.HttpMethod == "POST")
{
if (string.IsNullOrEmpty(mUserDetails.UserName))
{
ModelState.AddModelError("UserName", "Please enter your name");
}
if (!string.IsNullOrEmpty(mUserDetails.UserName))
{
Regex emailRegex = new Regex(".+@.+\..+");
if (!emailRegex.IsMatch(mUserDetails.UserName))
ModelState.AddModelError("UserName", "Please enter valid email");
}
if (string.IsNullOrEmpty(mUserDetails.Password))
{
ModelState.AddModelError("Password", "Please enter your password");
}
if (string.IsNullOrEmpty(mUserDetails.Address))
{
ModelState.AddModelError("Address", "Please enter your address");
}
if (string.IsNullOrEmpty(mUserDetails.MobileNo))
{
ModelState.AddModelError("MobileNo", "Please enter your mobile no");
}
if (!mUserDetails.TermsAndCondtionAccepted)
{
ModelState.AddModelError("TermsAndCondtionAccepted", "Please accept the terms");
}
if (ModelState.IsValid)
{
return View("SuccessfullPage");
}
else
{
return View();
}
}
return View();
}

Note :

ModelState: Gets the model state dictionary object that contains the state of the model. As per below, we can see that input values listed in the model-state.

Index :

@model ExplicitModelvalidation.Models.UserRegistrationModel
@{
ViewBag.Title = "Explicit Server Side Validation";
}
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>

<h2>Explicit Server Side Validation</h2>
@using (Html.BeginForm())
{
<fieldset><ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName, new{maxlength = 20})
@Html.ValidationMessageFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new{&nbsp;&nbsp; &nbsp;maxlength = 20})
@Html.ValidationMessageFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.Address)
@Html.TextAreaFor(m => m.Address, new{&nbsp;&nbsp; &nbsp;maxlength = 150})
@Html.ValidationMessageFor(m => m.Address)
</li>
<li>
@Html.LabelFor(m => m.MobileNo)
@Html.TextBoxFor(m => m.MobileNo, new{&nbsp;&nbsp; &nbsp;maxlength = 10})
@Html.ValidationMessageFor(m => m.MobileNo)
</li>
<li>
@Html.CheckBoxFor(m => m.TermsAndCondtionAccepted) I accept the terms & conditions
@Html.ValidationMessageFor(m => m.TermsAndCondtionAccepted)
</li>
</ol>
<input type="submit" value="Submit" />
</fieldset>
}

Explanation:

while pressing the submit button, it will post the data. If input data is not valid then it will add error to model-state using AddModelError() using ModelStateDictionary class

Output :

 

After pressing the submit button, it will post the data.If input data is not valid then it will show the error msg using @Html.ValidationMessageFor

Here , In controller i am using  if (Request.HttpMethod == “POST”) instead of checking ispostback. Using this we can use same action method for loading and validating using Html.BeginForm()

Caching in MVC

Different types of Caching Part 1

Why caching needed?

  • If many user are trying to accessing the site, it means your server has so many requests by the user, If every request hit the server for the response then it will lead to performance issues.
  • For example,if a page may contain some static information in your web site, in this scenario we can cache those content and don’t force your server to get them from data base in every request.This will increase your perfomance.

Advantage of Caching

  • Reduce Database and hosting server round-trips
  • Reduce network traffic
  • Improve performance

Remember while using Cache :

  • While caching of dynamic contents that change frequently, set minimum cache–expiration time.
  • Avoid caching for contents that are not accessing frequently.

Output Cache Filter :

It’s used to cache the data that is output of an action method.In default, this will cache the data upto 60 seconds.After 60 seconds, Asp.Net MVC will execute the action method again and start caching the output again.

Let we see with example..

Controller :

public class OutputCachingController : Controller
{

[OutputCache(Duration = 20, VaryByParam = “none”)]
public ActionResult Index()
{
ViewBag.CurrentDateTime = DateTime.Now.ToString();
return View();
}
}

View :

@{  ViewBag.Title = “Index”;}
<h2>Index</h2>
<h1>@ViewBag.CurrentDateTime</h1>

Run the application, first time it will show the output like below

up to 20 seconds it will show the same time in the browser without changing after we refresh the page because it will not call the action method upto 20 seconds ( so no new time updated in the viewbag)

VaryByParam : This property enables you to create different cached versions of the content when a form parameter or query string parameter varies.

VaryByParam = “aadharsh”

If it find records matching “aadharsh” string then a cache will be created,if paremeter/querystring changes than it will replace the old one with new
content

Let we discuss about Donut caching and Donut Hole caching in Part 2

NonActionAttribute Class in MVC

What is NonAction Attribute ?

In ASP.NET MVC, every public method of controller is accessible through the url regardless of return type. If we create any public method in the controller which is not intend to response as like action method. But it also accessible through the browser ULR. To overcome this scenario, the NonAction attribute has introduced

“All methods in MVC are treated as a action method. “

Purpose of using :

  •  As per above statement, all public methods of a controller class are basically treated as action methods in Asp .Net MVC. The methods which are
  •  By using this we changing the default behavior.

Example

Both GetUserDetail are treated as action methods.

public ActionResult GetUserDetail(){
// some code inside here
return View();
}

public void GetUserDetail(){
// some code inside here
}

So overcome this we are using NonAction Attribute method

[NonAction]
public void GetUserDetail(){
// some code inside here
}

[NonAction]
public ActionResult GetUserDetail(){
// some code inside here
return View();
}

Now above two methods are treated as Non action method. 

Child Action Attribute in ASP.NET MVC 4

What is ChildActionOnly?

The ChildActionOnly attribute ensures that an action method can be called only as a child method from within a view. In simple, ChildActionOnly attribute make controller action method to consider as non-action methods (It treated as normal method).

Where to use ChildActionOnly?

  • ChildActionOnly it related with partial views but it is not compulsory. If decided not to access through url then we may declare action method as ChildActionOnly.
  • This attribute used to prevent the action method being invoked as a result of a user request, that is it prevent from accessing via url.

Creating a Child Action Method

Let we discuss with example,

public class ChildActionTestingController : Controller
{

[ChildActionOnly]
public ActionResult GetUserDetails(int userId)
{
//Your Logic Here !!!
return PartialView(“GetUserDetails”, null);
}
}

Here GetUserDetails method is non-action method. The GetUserDetails method cant able to access by URL like ChildActionTesting/GetUserDetails.

@Html.Action(“GetUserDetails”, “ChildActionTesting”)

After declare GetUserDetails as childactiononly attribute, then it can’t allow to access through url. If you try to access, it show the error msg like below. It will treat as a normal method.

“The action ‘GetUserDetails’ is accessible only by a child request.”

Using an Asynchronous Controller in ASP.NET MVC 4

Asynchronous controller enables us to create asynchronous action methods in our application. This allows us to perform long running operation without making the running thread idle. Asynchronous action methods are useful when an action must perform several independent long running operations.

Synchronous

In Synchronous, if you making request, then you will have to wait till the response, you may not do other process until it response.

Asynchronous

In Asynchronous , if you making request, then you don’t need to wait for the response and we can perform any other process/task. Whenever the response arrive, you can receive in call back delegate.

What is Thread starvation in WebServer ?

  • From above, the request from Request A, Request B are accepted and processing but Request C not able to get the thread because the size of the pool is 2 so this situation is called thread starvation.
  • In this case we may get Server Busy Error

As per MSDN, When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is blocked while the request is being processed, and that thread cannot service another request.

This might not be a problem, because the thread pool can be made large enough to accommodate many blocked threads. However, the number of threads in the thread pool is limited. In large applications that process multiple simultaneous long-running requests, all available threads might be blocked. This condition is known as thread starvation

If you have multiple long-running requests, all available threads might be blocked and the Web server rejects any additional request with an HTTP 503 status

(Server Too Busy).

To overcome this, ASP.NET MVC provide asynchronously call in controller/action

Here let we see the asynController

How to convert controller to asynchronously

To convert a synchronous action method to an asynchronous action method involves the following steps:
1) Before we deriving the controller from Controller, now we want to derive it from AsyncController. Controllers that derive from AsyncController enable

ASP.NET to process asynchronous requests, and they can still service synchronous action methods.

Example

We want to apply “Async” before controller like

public class AsynchronuosController : AsyncController

The “OutstandingOperations” property tells ASP.NET about how many operations are pending. It is needed because ASP.NET dont known how many operations were initiated by the action method or when those operations are complete. When OutstandingOperations property is zero, ASP.NET completes its process by(asynchronous operation) calling the Completed method.

Example

AsyncManager.OutstandingOperations.Increment();
AsyncManager.OutstandingOperations.Decrement();

If we calling two method inside the action then we want to increment by 2 (AsyncManager.OutstandingOperations.Increment(2))

Sample Program:

using System.Web.Mvc;
using System.Threading;

namespace Asynchronous_Controller.Controllers
{
public class AsynchronuosController : AsyncController
{
public void IndexAsync()
{
AsyncManager.OutstandingOperations.Increment(2);
Call1();
Call2();
}
public ActionResult IndexCompleted(string call1, string call2)
{
ViewData["Call1"] = call1;
ViewData["Call2"] = call2;
return View("Index");
}
void Call1()
{
Thread.Sleep(5000);
AsyncManager.Parameters["Call1"] = "call1";
AsyncManager.OutstandingOperations.Decrement();
}
void Call2()
{
AsyncManager.Parameters["Call2"] = "call2";
AsyncManager.OutstandingOperations.Decrement();
}
}
}