All posts by Thiyagu

How to use MVC Bind Attributes

 

What is Attributes ?

Attributes are classes that allow you to add additional information to elements of your class structure.

What is Bind Attributes ?

In ASP.NET MVC View that accepts user input and post information to a server. Bind Attribute allow  an option to restrict the properties(ie., model) that are allowed to be bound automatically.

Where can we use Bind Attributes ? :

Scenario :

For example we having model/properties for binding the EMP DETAILS as shown below

Model :

public class EmployeeDetail
{
public string EmpName {get;set;}
public string EmpAddress {get;set;}
public string Department {get;set;}
}

From above some employee have rights to enter Department but some employee not have such rights to add Department.  In such scenario we can easily do it form level by hiding the Department Details from the page/Separate page, In this scenario we can use Bind Attribute to eliminate this property to update in Model/Property/DB.

Example : We can achieve this in two ways

1) Handel in Action Level

2) Handel in Model Level

Let we discuss about Action Level :

In Action Level, we will restrict the property while receiving to method ( it will not filter in model)

controller :

In controller we can restrict particular property (department) as shown below

public class EmployeeDetailController : Controller
{

[HttpPost]
public JsonResult Save([Bind(Exclude = “Department”)] EmployeeDetail emp)
{
return Json(string.Format(“EMP DETAIL”, emp));
}
}

view

@using (Html.BeginForm(“Save”, “EmployeeDetail”, FormMethod.Post, new
{
@id = “saveEmpDetails”
}))
{
@Html.TextBoxFor(m => m.EmpName)
@Html.TextBoxFor(m => m.EmpAddress)
@Html.TextBoxFor(m => m.Department)
<input type=”submit” value=”Insert” name=”Insertaction”/>
}

OUTPUT :

Bind 1

Click insert button to view in debug mode, as shown In below the model restrict to bind the value for the Department.


Let we discuss about Model Level Restriction :

We can handel in Model as shown below

[Bind(Exclude = “Department”)]
public class EmployeeDetail
{
public string EmpName{get;set;}
public string EmpAddress{get;set;}
public string Department{get;set;}
}


NOTE :

  • Attribute will be executed before the action
  •  If we place [Bind(Exclude = “Department”)] above the class it will exclude Department from other class inside the particular Model page
  •  If we place it inside the class it will applicable to particular class



How to create Areas in MVC 4 with Razor

 How to use MVC Areas feature using Razor

 What is Areas ?

  •  In MVC we have default folders (view, model, controller…) structure, If application grew larger, then it will be complicated to maintain a modules and structure logic for the file in the solution.
  •  To overcome this, MVC provide areas,Using MVC area has its own folder structure which allow us to keep separate controllers, views, and models…

Creating Areas

Step 1:

To add an area to application, right-click on the project —> select Add —> Area option as shown below.

Step 2:

Enter the Module/Areas Name in the “Add name Prombt” as shown below

Click ADD button to create  structure(Areas) as shown below

Same way we can create more areas based on our modules…

Step 3:

Create Controller by right clicking the controllers folder then create view , as shown in below

Step 4:

Here we start discuss about “How to call Module_1(Areas) from main project”.

Here i am creating actionlink for calling the view inside the Module_1

@Html.ActionLink(“Go to Module-1 Index”,”Index”,”Module_1″,new {area =”Module_1″},null)

  • “Go to Module-1 Index” :   Name of link
  • Index : Name of the Action
  • Module_1 : Name of the controller
  • new {area =”Module_1″} : Name of the area

Step 5 :  Run the Application

OUTPUT :

By clicking the link, it will redirect to Module_1 (inside the Areas) as shown below

How to create custom HTML Helpers using MVC 4 Razor

What is HTML Helper ?

The HTML helper is a method that returns a string. ASP.NET MVC Framework itself contains extension methods for HtmlHelper class to have well structured helper methods separation. Asp .Net MVC allow more flexible to extend the HelmHelper class to create our own custom helper method. It promote the use of reusable code.

  • HTML Helper methods will return string as output. if we want to write your own Html Helper method we have to create extension methods for HtmlHelper class.
  • System.Web.Mvc.Html contain the extension methods for Html Helper method.

Creating Custom Html Helper methods

Step : 1

Let’s create our extension methods for HTML Helper as like below.

namespace CustomHelpers
{
  public static class HtmlHelperExtensions
  {
    public static MvcHtmlString CustomTextBox(this HtmlHelper htmlHelper, string name, string value)
    {
      var builder = new TagBuilder("input");
      builder.MergeAttribute("type", "text");
      builder.MergeAttribute("name", name);
      builder.MergeAttribute("value", value);
      return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
    }
  }
}

From the above code, we creating CustomTextBox extender method which going to  return the appended string to the view.

Step : 2

Next step, we want to include our Html Helpers class namespace under the base class (ie., System.Web.Mvc.WebViewPage)

<system.web.webPages.razor>

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc,

Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

<pages pageBaseType="System.Web.Mvc.WebViewPage">

<namespaces>

<add namespace="System.Web.Mvc" />

<add namespace="System.Web.Mvc.Ajax" />

<add namespace="System.Web.Mvc.Html" />

<add namespace="System.Web.Optimization"/>

<add namespace="System.Web.Routing" />

<add namespace="CustomHelpers"/>

</namespaces>

</pages>

</system.web.webPages.razor>

System.Web.Mvc.WebViewPage be the base class for the razor engine. So we want to refer the custom method under base class

Step : 3

Call our Custom Html Helper method in the index view as shown below. Our custom method accepting two parameter which is the name of the Input Type and value of the Input.

@Html.CustomTextBox(“custom_txtbox”,”Custom Helper Method”)

OUTPUT :

Run the application and view the source of the page in browser as shown below. Here the text box is generated using our custom helper method. We can call this Html Helper method any where with including custom attributes in it.

Reusing @helpers Method across multiple views in mvc

Here we going to discuss about how to make the @helper method can be reusable across all multiple views in our project. We can achieve this by placing .cshtml in the App_Code folder to make visible to access across the application.

.cshtml : (indside  App_Code)

<html>
<body>
@helper CretingMultipleRow(int loopvalue)
{
<table>
@for (int loop_index = 0; loop_index < loopvalue; loop_index++)
{
<tr id=@loopvalue>      <td>Calling helper Method : @loopvalue</td></tr>
}
</table>
}
</body>
</html>

In App_Code

Calling Method from the view

<html>
<body>
@HelperReusableMethod.CretingMultipleRow(5)
</body>
</html>

Explanation:  @HelperReusableMethod.CretingMultipleRow(5)

  • @HelperReusableMethod : Name of the .cshtml file inside the App_Code
  • CretingMultipleRow(5) : Name of the method inside the HelperReusableMethod view

Output :

 

Razor’s @helper syntax provides a simple way to encapsulate/bind rendering functionality into helper methods , you can re-use within individual view , or across all view within a project.

Creating reusable method using @helper in MVC Razor

What is HTML Helper ?

The HTML helper is a method that returns a string. ASP.NET MVC Framework itself contains extension methods for HtmlHelper class to have well structured helper methods separation. Asp .Net MVC allow more flexible to extend the HelmHelper class to create our own custom helper method. It promote the use of reusable code.

More about HTML Helper here.

Example : Reusable method using @helper

The @helper class enables us to easily create re-usable helper methods that can encapsulate in output function. This enable code reuse and more readable. It bind blocks of Markup (HTML) and Server-side logic into reusable page-level methods.

Syntax : @helper MethodName(parameters) { … }

As per below, we are creating a simple helper method in the view (CretingMultipleRows). The main role of the CretingMultipleRows method is to create a table based on the loopvalue input. Based on the code, we can make reuse of this helper method within the view.

Index .cshtml

<html>
<body>
@helper CretingMultipleRows(int loopvalue)
{
<table><tr id=@loopvalue><td>Calling helper Method :
@loopvalue</td></tr></table>
}
<table><tr><th>Creting Multiple Row</th></tr>
<tbody>
@for (int loop_index = 0; loop_index < 5; loop_index++)
{
@CretingMultipleRows(loop_index)
}
</tbody>
</table>
</body>
</html>

Output :

Difference between Html.RenderPartial vs Html.Partial vs Html.RenderAction vs Html.Action in MVC

In this post, we are going to discuss about Html.RenderPartial vs Html.Partial, Html.RenderAction vs Html.Action. Let we split this stuff in two ways  based on binding the static and dynamic content like Render partial and Action Partial .

Partial Vs RenderPartial

  • @Html.Partial(“Details”)  –  returns a String as an output
  • @{ Html.RenderPartial(“Details”); } –  returns void as an output

Action Vs RenderAction

  • @Html.Action(“ActionName”, “ControllerName”) – returns a String as an output
  • @{ Html.RenderAction(“ActionName”, “ControllerName”); } –  returns void as an output

Render vs Action partial

Let us discuss about the main difference between RenderAction and RenderPartial. RenderPartial will render the view on the same controller. But RenderAction will execute the action method , then builds a model and returns a view result.

Render Partial : Use Html.Partial when you are rendering static content.

Action Partial : Use Html.Action when handling dynamic Content/data.

Where to use Html.Partial and Html.Action

Html.PartialIf we need to display a static menu for all users from the partial view, then we can use Render partial.

Example:

View : Here we call the partial view from the view (passing model as input).

@Html.Partial(“_partialName”, model)

Html.Action: If we need to display different menu items based on the user level, then we can use Action Partial.

Example:

Controller:

public ActionResult CustomerDetail() {
return PartialView(new CustomerDetailModel());
}

View

@model Model
@Html.Action(“CustomerDetail”)

Difference :

1) @Html.RenderPartial and @Html.RenderAction is the best practice to use in most cases because the output has been written in the same TextWriter object.

2) In contrast to this, @Html.Partial and @Html.Action methods create their own TextWriter instances at every time and buffer all their content into memory.

3) @Html.Action and @Html.RenderAction method is the best choice when you want to cache a partial view.
@Html.Partial and Html.RenderPartial method is the best choice when you want to load new view.

4) The return type for @Html.Partial and Html.Action returns string type values
@Html.RenderAction and Html.RenderPartial returns is void

5) @Html.Partial and @Html.Action will useful when assign the content into a variable for other purpose…

 

Have a cool coding………

 

Difference between return View() ,return Redirect() and return RedirectToAction() in MVC

return View() :

It commend to generate HTML to display for the required view and render/send it to the browser

Example :

public ActionResult Index()
{
UserDetailModel obj = new UserDetailModel();
obj.CountryDetail = new List<Country>()
{
…….
};

return View(obj);
}

In this above code the view is  (it never call any controller) which is referring the Action Method.
This below also work like above

[HttpPost]
public ActionResult Index(string Name)
{
return MyIndex();
}

return Redirect()

It commend to redirect to specified URL instead of rendering HTML (ie., it redirect to new URL)

Example

[HttpPost]
public ActionResult Index(string Name)
{
return Redirect(“Home/TIndex”);
}

return RedirectToAction()

It commend to redirect to specified action instead of rendering HTML

Example

[HttpPost]
public ActionResult Index(string Name)
{
return RedirectToAction(“TIndex”);
}

Note :

1)  Return View doesn’t make a new requests, it renders the view without changing URLs in the browser’s address bar. (ie., simple like Server.Transfer() )

2)  Return RedirectToAction makes a new requests and URL in the browser’s address bar is changed (ie., simple like Response.Redirect() )

RedirectToAction(“CustomerDetail”, “Customers”, new { CustomerID = 1001 })

In this above,it will generate the URL for you based on your route table.CustomerID will pass to the customerDetail action method under the CustomerFolder

3)  Redirect also work same as RedirectToAction , but you have to mention full URL to redirect

 

Different way to call controller from view using MVC Razor

Different way to call controller from view

Syntax    @Html.Action(“action”, “controller”, parameters)

Method : 1

@using (Html.BeginForm(“Save”,”ControllerName”, FormMethod.Post))
{
@Html.TextBoxFor(model => m.Name)
<input type=”submit” value=”Save” />
}

Note :

  •   “Save” be the name of the Html form. We can also use Ajax.BeginForm() instead of Html.BeginForm
  •    Html.BeginForm is nothing but Html form

Method : 2

From Jquery

1) var url = ‘@Url.Action(“ActionName”, “ControllerName”)’;
window.location = url;

2) $(this).load(“@Url.Action(“ActionName”, “ControllerName”)”);

Note :

  •  2nd way is used for loading the partialview to the mainview

Method : 3

@Html.ActionLink(“ActionLinkName”, “ActionName”, “ControllerName”)

 

 

 

How to use WebGrid from PartialView using Razor

WebGrid is used to display the data with paging and sorting. In this article, we will discuss about how to load the data to webgrid and would like to explore how can to use default paging and sorting.

Controller

Let we create simple controller which will return the UserDetailModel to the view. From the view we can bind the WebGrid using the model data.

public ActionResult LoadGridinPartialView()
{
UserDetailModel obj = new UserDetailModel();
obj.CountryDetail = new List<Country>()
{
new Country() { CountryId = 1, CountryName =  "INDIA" },
new Country() { CountryId = 2, CountryName= "US" },
new Country() { CountryId = 3, CountryName= "Russia" },
new Country() { CountryId = 4, CountryName= "UK" }
};
return View(obj);
}

View

From the below code, just passing the model data to the partial view for loading WebGrid.

@model RegistrationForm.Models.UserDetailModel
@{
ViewBag.Title = "Load WebGrid in Partial View";
}
<h2>Load Grid in Partial View</h2>
@{
Html.RenderPartial("_LoadGrid", Model.CountryDetail);
}

Note :

   From Html.RenderPartial(“_LoadGrid”, Model.CountryDetail);

  •    _LoadGrid being created under the “Shared” folder
  •    Model.CountryDetail is model information being passed as parameter to the partial view

PartialView (_LoadGrid)

_LoadGrid Partial view bind the WebGrid by receiving model data from the view.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>_LoadGrid</title>
</head>
<body>
<div>
@{

var grid = new WebGrid(source: Model, rowsPerPage: 3, canPage: true, canSort: true);
<div id="grvCountry">
@grid.GetHtml(
fillEmptyRows: false,mode: WebGridPagerModes.All,
htmlAttributes: "width:100%",firstText: "<< First",
previousText: "< Prev",nextText: "Next >",
lastText: "Last  >>",
columns: new
[] { grid.Column("CountryId", header: "Country ID"), grid.Column("CountryName", header: "Country Name") } ) </div> } </div> </body> </html>

OUTPUT

How to create simple WebGrid in MVC (Razor engine)

Create simple WebGrid in MVC (Razor engine)

Controller

public class WebGridExampleController : Controller
{
public ActionResult Index()
{
UserDetailModel obj = new UserDetailModel();
obj.CountryDetail = new List<Country>()
{
new Country() { CountryId = 1, CountryName =  “INDIA” },
new Country() { CountryId = 2, CountryName= “US” },
new Country() { CountryId = 3, CountryName= “Russia” },
new Country() { CountryId = 4, CountryName= “UK” }
};

return View(obj);
}
}

View

@model RegistrationForm.Models.UserDetailModel
@{
ViewBag.Title = “Index”;
}
<style type=”text/css”>
th
{
font-size: 14px;
font-weight: normal;
color: #039;
padding: 10px 8px;
}
table
{
font-family: arial,sans-serif;
font-size: 11px;
border-width: 1px;
border-color: black;
}
table th
{
background: #D3D3D3;
border-width: 1px;
border-style: solid;
border-color: black;
}
table td
{
background: #AFEEEE;
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: black;
}
.foot
{
text-align: center;
}
</style>
<h2>
Country Details</h2>
@{

var grid = new WebGrid(source: Model.CountryDetail, rowsPerPage: 3, canPage: true, canSort: true);

<div id=”grvCountry”>
@grid.GetHtml(
fillEmptyRows: false, mode: WebGridPagerModes.All,
htmlAttributes: “width:100%”, firstText: “<< First”,
previousText: “< Prev”, nextText: “Next >”,  lastText: “Last  >>”,
columns: new

[]
{  grid.Column(“CountryId”, header: “Country ID”, style: “column1”),
grid.Column(“CountryName”, header: “Country Name”, style: “column2”),
   })
</div>
}

Output :

Explanation:

      In first line(var grid…), we are assigning the mode,
rowperpage : how many rows want to display in Webgrid,
canpage : here want to set the default pagination in the webgrid to be true/false
canSort  : here want to set filter based on the column header (true/false)

Model.CountryDetail : Here being binding the other class inside the UserDetailModel model…