Category Archives: MVC

Creating Scaffolding template for Cutom Model

Creating Custom Scaffolding

What is Scaffolding in MVC

Scaffolding is a Templates for Create, Delete, Edit ,Details. It will reduce the time for developer for creating controller,view for the specific model
This is a Scaffolding package for ASP.NET which is installed via NuGet using ‘Install-Package MvcScaffolding’ command

Using Templates

Step : 1

Create Sample web project

Step : 2

Create custom model as like below

scaff1

Step : 3

Here we going to install the scaffolding in our project.
GoTo Tools –> Library Package Manager –> Package Manager Console as shown below to install the scaffolding

To install Scaffolding, type below command in below console
cmd : Install-Package MvcScaffolding

Step : 4

Next creating template against custom model by using below command

cmd : Scaffold controller EmployeeModel


After executing the command in console, it will create the template for CRUD Operation as shown below

 

Output :

After generation of Views, run the application. Now u can perform CURD Operation without extra code.

Difference between POCO and DTO model

Really, I spend more time to understand Poco and DTO with a lot of confusion and questions. After understanding I decide to post immediately to my blog.

What is POCO?

  • POCO stands for Plain Old CLR Object.It provides freedom to define an object model in which objects does not inherit from specific base classes
  • POCO data classes, also known as persistence-ignorant objects, it refers to an object do not have any persistence concerns
  • It mainly has a control over implementation and design
  • A POCO is a BO (Business object). We can implement validation and any other business logic can occur here.
  • POCO have state and behavior.

What is Persistence ignorance in POCO

It means (layers) it does not depend on the design of the database, IE., type of database, type of database object.

Example for POCO Model

public class Customer {
public int CustomerID
{ get; set; }
public string CustomerName
{ get; set; }
public string CustomerGender
{ get; set; }
}

What is DTO?

  • Stands for Data Transfer Object, its Main purpose is to transfer data.
  • It just stores data. It is a lightweight container used for transferring data between layers.
  • There will be no effect on application if entity changed or modified (based on the Database structure)

Example for DTO Model

public Customer()
{
CustomerID = Int_NullValue;
CustomerName= String_NullValue;
CustomerGender = String_NullValue;
Address = String_NullValue;
}
Difference between POCO and DTD

  • POCO has state and behavior, but DTD has only state (it does not contain behavior IE., method)
  • POCO describes an approach to programming, where DTO is a pattern that is used to move data using objects.

How to Apply Styles with Html Helpers in MVC4 Razor

How to Apply Styles with Html Helpers in MVC4 Razor

In this article let us discuss how to apply CSS styles using HTML helpers.

  • using Inline
  • using Class

Using Inline CSS

From the below code, we can directly add the styles.

@Html.TextBox(“Name”, “”, new{style = “width:80px;height:20px;background-color:#F0F0F0 ;”})

using CSS Class

Another way, we can call the css class name instead of style.

.txtbox {
width: 100px;
height: 75px;
background-color: #F0F0F0;
border:1px solid black;
}

@Html.TextBox(“txtName”,””, new{@class = “txtbox”})

Note :

Correct Way:

@Html.TextBox(“txtName”,””, new{@class = “txtbox”})

Wrong Way:

@Html.TextBox(“txtName”, new{@class = “txtbox”}) – It will not apply the style to the textbox

From the above code new{@class = “txtbox”} want to be third parameter , if you not going to pass the value as second parameter then we need pass null/Empty value.

Output:

MVC Razor : Different way of getting @Html.TextBox value from view to controller

In this article we are going to discuss about the different way of getting the value from the textbox using MVC razor.

Index.cshtml

Here we had included the Html.TextBox in the Index.cshtml.

<div>
@using (Html.BeginForm(“Index”, “Index”, FormMethod.Post))
{
@Html.Label(“Enter Your Name”)
@Html.TextBox(“txtName“)
<input type=”submit” id=”btnSubmit” name=”Submit” />
}
@ViewBag.Name
</div>

Method 1: Using the Name(id) of the @Html.TextBox

IndexController :

We having a Index action method for getting the textbox value from the view.

public ActionResult Index(string txtName)
{
ViewBag.Name = txtName;
return View();
}

  • In this method we can get the value of textbox  using id/name. ie., txtName.
  • Getting value type must be string, else it will show the following error ( if we change type to int)

Method 2: Using the FormCollection

FormCollection does not contain key/value pairs, just having an id/name. Using the name/id of the text box we can get the value as shown below..

public ActionResult Index(FormCollection Form)
{
ViewBag.Name = Form[“txtName”];
return View();
}

Below image shows quick view of formcollection

 

Keep cool coding….

How to handle Multiple submit buttons in the same form/page

Handle Multiple submit buttons in single page

Scenario :

For example, we have a login form with “sign in”,”sign up” and “cancel” button. In this scenario, “sign in” will redirect/do some action,same like sign up and cancel. Lets we discuss how to handle multiple button in same form (calling different action method).

View :

Let we create view with three submit button.

Controller

Here i am going to create three separate action method for signin,signup,cancel for capture the click event in the controller.

[HttpPost] [MultipleButton(Name = "action", Arg= "signin")] public ActionResult signin() { return RedirectToAction("Index", "signin"); }
[HttpPost]
[MultipleButton(Name = "action", Arg= "Signup")]
public ActionResult Signup()
{
return RedirectToAction("Index", "Signup");
}
[HttpPost]
[MultipleButton(Name = "action", Arg= "Cancel")]
public ActionResult Cancel()
{
return RedirectToAction("Index", "Home");
}

Custom ActionNameSelectorAttribute  :

Here we going to implement a custom ActionMethodSelectorAttribute to check which button submitted the form.This contains values posted in the form in a NameValueCollection object.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultipleButtonAttribute : ActionNameSelectorAttribute
{
public string Name{get;set;}
public string Arg{get;set;}
public override bool IsValidName(ControllerContext controllerContext,
string actionName, MethodInfo methodInfo)
{
bool isValidName = false;
string keyValue = string.Format("{0}:{1}", Name, Arg);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
if (value != null)
{
controllerContext.Controller.ControllerContext.RouteData.Values[Name] = value;
isValidName = true;
}
return isValidName;
}
}

Note : While clicking the button, MultipleButtonAttribute method will execute first to know which action Mthod to call

OUTPUT :

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 :



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 :