-->

Tuesday, March 8, 2016

Customization of CreateUserWizard Control in ASP.NET C#

Create User Wizard control is used to store information of the user or visitor into the database table. ASP.net provide the control through this we can store limited information of the client into the database table. But we can change its user interface. You can say customization of Grid View. When we drag it on design window then its look like:


Customization of CreateUserWizard Control

Select Create User Step link by using "show smart tag". After that you can make some changes in fields. Like if You want to remove "Security Answer" and Security Question. Suppose you have to remove it then your interface look like:

 remove "Security Answer" and Security Question.

But when you run it then you get error like :

Default Membership Provider must be specified.

[Solution]
Add tags in web. config file.
<system.web>
<membership>
      <providers>       
        <clear />
      <add requiresQuestionAndAnswer="false" name="AspNetSqlmembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="DefaultConnection" applicationName="Application"/>
      </providers>
    </membership>
</system.web>
Code Generates the following output
Customization of CreateUserWizard Control in ASP.NET C#

Wednesday, September 10, 2014

How to Bind DropDownList with Enum MVC

Earlier article was about to bind DropDownList with simple select list of type selectlistitems. These select list may by any type of list either from database or temporary for that view only. In this article we will create an enum, then create a select list through that enum and finally will bind that to drop-down list.

Create an Enum like I have, named OptionType

enum OptionTypes
{
value1,
value2,
value3,
value4
}

After creating enum, write a class that will work like a helper to create select list for that enum:

public static class EnumHelper
{
// Get the value of the description attribute if the   
// enum has one, otherwise use the value.  
public static string GetDescription<TEnum>(this TEnum value)
{
var fleid = value.GetType().GetField(value.ToString());

if (fleid != null)
{
var attributes = (DescriptionAttribute[])fleid.GetCustomAttributes(typeof(DescriptionAttribute), false);

if (attributes.Length > 0)
{
return attributes[0].Description;
}
}

return value.ToString();
}

/// <summary>
/// Build a select list for an enum
/// </summary>
public static SelectList SelectListFor<T>() where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null
: new SelectList(CreateSelectList(t), "Value", "Text");
}

/// <summary>
/// Build a select list for an enum with a particular value selected 
/// </summary>
public static SelectList SelectListFor<T>(T selected) where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null
: new SelectList(CreateSelectList(t), "Text", "Value", selected.ToString());
}

private static IEnumerable<SelectListItem> CreateSelectList(Type t)
{
return Enum.GetValues(t)
  .Cast<Enum>()
  .Select(e => new SelectListItem { Value = e.ToString(), Text = e.GetDescription()                            });
}
}

Go to your controller and write the line as I have:

ViewBag.values = EnumHelper.SelectListFor<OptionTypes>();

Open your view page and write

@Html.DropDownList("values");

Run this view in browser and check, your drop-down list has been bind. This will create a simple list named “values” as specified as parameter. If we want to create a drop-down list for a model then:

@Html.DropDownListFor(model => model.property, (IEnumerable<SelectListItem>)ViewBag.values, new { html parameters })

This will bind this drop-down list as strongly with the property of the model.

Saturday, August 30, 2014

Basics about JQUERY, Types of Selectors

To change the web page after rendered programmer has to change the coding done for the page and then refresh again. To manipulate a web page after it has been rendered without change the coding part, programmer often uses Jquery. Jquery library makes it easy to change the functionality of web page smoothly.

Jquery library provides tools that enable user to interact with the page or to include animations on page. This article will describe about some basic elements of jquery library, later we will implement some functionality on the page with tools provided by the library. To user jquery library programmer must have a reference on the web page or layout file.

Selecting an element/control on which programmer will perform some action, jquery library provides selectors. These selectors can select any element/control on the basis of their id, class or their type as per the requirement.

Showing an alert just after loading of the page, jquery provides an in-built function. Programmer can enable any functionality on loading of the page using below syntax.

$(document).ready(function(){
alert("page loaded");
});

First we need to know about how to select an element/control in jquery
Element Selector: To select an element on the page like <p/> (paragraph tag), <a/> (anchor tag), <input /> or any other element, programmer has to write something following below syntax:

$(document).ready(function(){
$('p').click(function(){
alert('<p> element selected');
});
$('a').click(function(){
alert('<a> element selected');
});
$('input').click(function(){
alert('<input> element selected');
});
});

Id selector: to select a control on basis of the id of that element, programmer needs to know about id selector. '#' symbol is used to select according to control's id like "$('#btnInput')" will select the control having id "btnInput". As we know that each control has its own id on the page and that is unique.

$(document).ready(function(){
$('#btnInput').click(function(){
alert('input button clicked');
});
});

Class selector: to select control(s) according to their CSS class property, this selector is used. Suppose we have multiple buttons having same class i.e. "button" so to apply some change on all of then we can do by using this selector.

$(document).ready(function(){
$('.button').click(function(){
alert('button clicked having class "button" ');
});
});

There are many jquery selectors in the library, we will use them one by one in later articles.

How to Create Layout page and set for View: MVC

After creating default MVC application in Visual Studio there is a default layout file has been added in shared folder under views having name _Layout.cshtml. This file is used to provide consistent look on all of the pages having default layout page set. Changes done in this file will set for all the pages/views under this layout.

The above extension ".cshtml" is used only in case of Razor and this will be changed for aspx views. Programmer can even change this layout file as per requirements or can use multiple layout files according to the roles/group  defined. All the scripts, styles and custom files must be included in this layout file if necessary for all views.

If Programmer don't want to use any layout for the view then "Layout = null" must be set in the view page. This feature can only be set for that particular view. Now to create new layout file programmer have to add new item as "MVC Layout Page(Razor)" and change the name if required otherwise default will be used.

MVC set layout null


After adding the layout file create html and use “@RenderBody()” statement wherever you want to render the body of view page which will have this layout. Whatever change we do in this file, will be changed for all the views having this file as a layout.

Whenever programmer adds a new view there is an option for using a layout or master file with a checkbox and browse button. Check that checkbox and browse for the layout file created above. This will set that file as a layout for that new view.

MVC set null in new view

Wednesday, July 30, 2014

How to Submit data on DropDown Selection changed in MVC Razor

Submitting the form by button, programmer have to assign only the type of that button and on click this button all the data can be get on the server side. On drop-down change we have manually submit the form by either specifying "OnSelectionChanged" event or some jquery functions.

In earlier article I have created DropDownList in MVC, to submit the form we can simply use only submit function on change event of the list.

@Html.DropDownList("ddlname", "List to bind", "--default title--", new { onchange = "submit();" })

After writing this code on change it will post all the data on the form to server-side but programmer have to use same name in action method as used here “ddlname”. When we use view-model to bind the data then dropdown list’s code will be changed as:

@Html.DropDownListFor(model => model.Property , "List to bind", "--default title--", new { onchange = "submit();" })

This code will contains the value of the property of model as used here. The value will submit on change the selection of this drop-down list. Programmer can change other controls value by using this code.

Suppose we have to select country, state and city on the form in hierarchy manner. On change the country, states drop-down list should change and on change of state, city drop-down list should change. By implement this functionality we can use this submit functionality.

Saturday, June 28, 2014

Returns Radio Button Input element using Html.RadioButton() handler: MVC

Html.RadioButton() handler, used to return radio button input element to be input true or false value by user. Checked radio button will return true and un-checked will return false, otherwise it returns null to store/use the value.

Html.RadioButton() handler method is used to present mutually exclusive option i.e. true of false. Using this radiobutton method makes it easy to bind to view data or model is so easy in compare to using simple input radio element. This handler provides mostly same features as Html.CheckBox() handler discussed earlier.

Parameters


  • htmlHelper: specify html helper instance that this method extends.
  • name: specify name of input element used to access the value in controller.
  • value: specify value of radio button element. If none is assigned then this attribute is used to access the value.
  • isChecked: to be set true of false for radio button. True to select the element, OW false.
  • htmlAttributes: specify an object that contains html attributes to set for the element.
     e.g Html.RadioButton(“gender”)

Html.RadioButtonFor(…)

Having the same functionality as Html.RadioButton() but it returns radio button element for each property passed via the model from controller’s action. This handler have two types of type parameters i.e. TModel (specify type of model) and TProperty (specify type of value).

Parameters

  • htmlHelper: specify html helper instance that this method extends.
  • expression: used to identifies object containing the property to render.
  • value: specify value of radio button element. If none is assigned then this attribute is used to access the value.
  • htmlAttributes: specify an object that contains html attributes to set for the element.

e.g Html.RadioButtonFor(model=>model.Gender)

Render radio button input for the property gender passed via controller. Submitting form will assign the value of this radio button to model’s gender property to be accessed in the controller’s action.

Returns Password input element using Html.Password() Handler: MVC

Html.Password() handler, used to return password input element to be input password value by user. This article describes about to using password html helper that will make text unreadable by other users in MVC application.

Like all other input elements, using Html.Password() html handler users are not able to read input value. This handler is mostly used in login process of any ASP.Net MVC application because of some special features of this helper.

This helper commonly have following features:

  • Text input in the control is un-readable.
  • Does not allow user to copy the text input in the control.
  • Does not repopulate its value from ModelState object.

Parameters


  • htmlHelper: html helper instance that this method extends.
  • name: used to specify the name of form field that may be used to look up the value.
  • value: specify the value of this element.
  • htmlAttributes: specify html attributes to be set for the element like placeholder, id, any class or other values.
Overall this will generate an input element having the type password on the page:
<input type=”password” runat=”server” id=”password” />

Html.PasswordFor(…)

Provide same functionality but used to render password input element for each property passed via model. Here the model is the class for which the view is to be created. This handler have two type parameter i.e. TModel (specify type of model) and TProperty (specify type of value).

Parameters


  • htmlHelper: html helper instance that this method extends.
  • expression: used to identifies object that contains property to render.

Html.PasswordFor(model=>model.Password)

this line will render an input element of type password having id "Password" passed by the model. After submitting form, the value of this element will assigned to the password field of the model and can be easily accessed for further use.

Monday, June 9, 2014

Returns CheckBox Input element using Html.CheckBox() Handler: MVC

Html.CheckBox() handler, used to return check box input element to be input true or false value by user. Selected checkbox will return true and un-selected will return false, otherwise it returns null for the programmer to store/use the value.

In compare to other input element, this handler is easy to bind to with the data source provided by the programmer for the page. This handler/method have its own parameters list as Html.Label() or Html.TextBox() handlers have.

Parameters

  • Name: specifies the name of form field. It is string type of parameter.
  • isChecked: programmer should pass true to select the checkbox, otherwise false. As the name implies it is Boolean type of parameter.
  • htmlAttributes: specifies an object that contains all the html attributes to set for the element as discussed earlier.
@Html.CheckBox("isMarried", true);

This line will return an check box input element on the page with checked true value, as passed with the method. The name of form field will be isMarried, used to get the value of this element.

@Html.CheckBoxFor(…)

This handler works same as above but for a particular property in the object specified in the expression. This handler is used to return check box input for only the bind to property exists in the mode passed by an action to this view page.

Parameters are almost same except the expression which is a predicate to be bind this element with the specific property.

Let’s suppose this view page is bind to a model of type student having the properties like name, age, isMarried and etc. To bind this check box handler programmer have to write the following line of code:

@Html.CheckBoxFor(model => model.isMarried, false)

This handler now binds to isMarried property of the model and by default it will be un-selected on the page.

How to Execute Server-side code based on condition: Razor

Razor syntax helps developers to execute the code based on some condition specified like if-else or may be switch statement. Programmer can easily decide, which statement(s) need to be executed, based on the condition given within if statement.

IF-Else Statement:

To test a condition by using IF statement, write a condition in if parenthesis, start an IF block and at the last write the statements to be executed in the curly braces i.e. called if block. This block will be execute when the given condition is true, to execute some statements on the false of this condition, programmer have to write ELSE part.

@{
    var value = 5;
}

@if (value >4)
{
    <p style="font-size:20px; font-weight:bold">Value is greater than "4"</p>
}
else
{
    <p style="font-size:20px; font-weight:bold">Value is less than or equal to "4"</p>
}

In the above block variable value have initial value 5. According to the given condition the first block will execute. If we change the value as 4 then it will execute the second block i.e. ELSE part of the statement. What if we have some more condition to be check, either we have to use if-else if-else condition or switch statement.

Switch Statement

To execute statements based on number of individual conditions, switch statement is used by the developer. Switch statement specifies some cases to be check by compiler and execute the statements written in particular case on which condition matches. Just notice the following lines of code:

@switch (value)
{
    case 5: <p>Value is: 5</p>
        break;
    case 4: 
    case 3: 
    case 2: <p>Value is >= 2 and <=4</p>
        break;
    case 1: <p>Value is: 1</p>
        break;
    default: <p>Value is either <1 or >5</p>
        break;
}

Here, I have specified individual statement for case 1 and 5 but a single statement for case 2, 3 and 4. This feature of switch statement is used when a single statement is to be executing for one or more cases. Now for value = 2 /3/4 a single statement “Value is >= 2 and <=4” will execute.

Like in if condition the else part will execute when false, switch statement provides “default” case for all other case except specified. This value can also be changed or assigned at runtime to execute code dynamically.

Wednesday, June 4, 2014

Return Text Input Element using Html.TextBox() handler: MVC

Html.TextBox() handler used to return text input element on the page at run time. It supports some types of parameters discussed and also have some more options to returning text inputs on the page. Mostly it is of two types listed below with their specification and uses.

@Html.TextBox(Parameter collection...)

This html handler is used to return text input element to be input some values by user like name, age, address and more. As this element is used like a method in Asp.Net MVC, this may have some parameters to be passed with it. This handler returns only an input field in the form of

<input type="text" name="name" id="id" />

Following is list of parameters this handler may used:
  • Name: used to specify name of form field (can be used to find control on page) and this parameter is of string type.
  • Value: this parameter is of type object and used to specify value of text input element. If this value is null then this element will get the value from viewdata dictionary otherwise model data dictionary.
  • Format: used to format the input value in prescribed format string. To format the text input in date form, programmer may use "{0:d}"
  • Html Attributes: the object contains html attributes to set for the element like class, font size and many more attributes.
    @Html.TextBox("txtName", "Student Name", "{0:d}", new { @class = "txtClass" })

@Html.TextBoxFor(Parameter collection...)

The main difference between @Html.TextBox() and @Html.TextBoxFor() is this handler use prediction to resolve the value to be shown. All the remaining parameters are same in both the handlers.

This method is used when programmer binds this page through a model class (having some properties). Programmer can specify more html attributes within the related section.

For example the following line of code will fix the max length of textbox
@Html.TextBoxFor(m=>m.Name, new { maxlength = "20" })

To disabled the textbox just specify the disabled attribute like written below:
@Html.TextBoxFor(m=>m.Name, new { disabled = "disabled" })

Return Label Element using Html.Label() Handler: MVC

Html.Label() handler used to return label element on the page at run time. It supports some types of parameters discussed and also have some more options to returning labels on the page. Mostly it is of three types listed below with their specification and uses.

Html.Label(parameter collection...)

This Html handler is used to return label element with property name specified by the parameter expression. Here is collection of parameter this html handler used:

  • Expression: used to identify the property to display.
  • label text: specify the text of label to display.
  • Html Attributes: this parameter is type of object, contains all the elements to be set for this label element.
    @Html.Label("stName", "Student Name", new { @class = "lblClass" })

Html.LabelFor(parameter collection...)

This handler is used for showing the label element of property passed from the model, the page bind. For example the page is bind to student model and we bind this handler with student name then this handler will show the name of student like shown below:

@Html.LabelFor(model => model.Name)
Here model represent the class name passed to bind this view. This parameter must be defined in prediction type as shown in the above code, without prediction it will show an error. Remaining parameters are same as Html.Label() handler.

@Html.LabelForModel(parameter collection...)

This handler returns a label whose for value is that of the parameter represented by the model object. It is mostly used in editor templates in MVC View. e.g.

@Html.LabelForModel() - it shows the label element for the string property of model bind with this view.

Variable, Conditions and Looping in Asp.Net Razor: C#

Like all other programming languages, variables are named entities used to store data to be used in particular scope. Declaration of variables must follow all the rules described in other languages like must begin with alphabetic character, cannot contain white spaces or any reserved character.

Variables can be declared by their specific data type or "var" keyword. Variables may use all the operators as other languages use. Following lines of code will declare some variables of different data types:

// Variables having var datatype
var name = "Computer Programming"
var url = "dotprogramming.blogspot.com"
var authors = 10
var estb = 2013

//Datatypes accordingly
String name = "Computer Programming"
String url = "dotprogramming.blogspot.com"
int authors = 10
DateTime estb = 2013

Razor syntax also supports conditional expressions i.e. if...else statement to be used some lines of code accordingly. Following lines of code will specify an if...else code block which with always show the true case, because of the condition.

@{ if (true)
   {<p>This is true case</p>}
   else
   {<p>This is false case</p>}
}

By using above type of code, programmer can easily specify the divisions on individual condition. Like this conditional statement razor also supports looping statements i.e. For loop, for-each loop, while loop etc. To be execute some lines of code multiple times programmer need to use these looping constructs.

Following line of code will write the string ("dotprogramming.blogspot.com") 10 times on the page:

@{ for (int i = 0; i < 10; i++)
   {
       <p><a href="https://dotprogramming.blogspot.com">Computer Programming @(i+1) </a></p>
    
   }
}

Running these line of code will show you 10 links of the same url (as specified):

Variable, Conditions and Looping in Asp.Net Razor: C#

Generating same output from for-each loop, programmer need to write something like these lines of code:

int[] array = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

foreach (var item in array)
{
   <p><a href="https://dotprogramming.blogspot.com">Computer Programming @(item) </a></p>
}

Introduction to Mark-Up Language: Asp.Net Razor

Razor, mostly used language in Asp.Net MVC, is not a programming language but it is a server-side mark up language. It is basically used to let the programmer embed server based code in to web pages.

By running on the server-side, Razor code can perform complex tasks including database accessing. Server executes this code inside the page before returning to the browser at the time of calling a particular page. The main advantage of this markup language is, it supports c sharp (C#) as well as visual basic (VB).

Here are some rules/instructions to be follow when writing razor language with c#:

  • Declarations of variables/functions will start with @
  • Code blocks are enclosed in @ {... }
  • Statements will end with semicolon (;)
  • Remember c# code is case sensitive
  • Comments can be written within @* ...... *@

Following line of code will explain you a brief knowledge about razor syntaxes:

@* Commented Section
Below are some line of code which will use two variables declared in razor and then use them to show title and description of the page.
*@

@{
    var title = "This is this page's title";
    var description = "The description about this page";
}

<div>
    <p>Title: @title</p>
    <p>Description: @description</p>
</div>

<!-- Comments can also be written like this -->

The first block of code is used for commented lines as written as heading. Second block is used to declare two array i.e. title and description that can be used further in the code. The last code is html code and simple div and p tag are placed there to write the values of above declared variables.

Razor provides mostly all the server-side objects with all these methods they can have. To show current date/time razor syntax will be:

<p>
    Today Date:  @DateTime.Today 
    Time:  @DateTime.Now.TimeOfDay
</p>

There are many more we have to learn about razor syntax like variables, conditional statements, looping constructs etc.

Tuesday, May 27, 2014

How to Render HTML Controls in View: Asp.Net MVC

Asp.Net MVC provides a way to write simple programming syntaxes and HTML Helpers convert them in to HTML at runtime to be simply open the pages at client end. These provides generates html and return result as a string.

Like other web form controls in Asp.Net, HTML helpers are used to modify HTML, but HTML Helpers does not have an event model/ view state as web form controls have. Programmer can use these helpers by using built in HTML property of the view that are in System.Web.Mvc.Html namespace. We can create our own Html helpers or use built-in provided in the specified namespace.

HTML helpers have methods for creating forms, rendering partial views, performing input validation etc. Here are some mostly used html helpers:

HTML Links

These type of links are used to render an html link on the page, but in MVC they create a link to redirect on a particular action of the controller.
        @Html.ActionLink(“Text to Display”, “Action-name”)

The first parameter is used to specify the text to be displayed for user and second parameter is used to specify the action-name to which user will redirect after click.

HTML BeginForm

To place a form element on MVC, following syntax is used that will create an HTML form with some parameter values listed below.

@using (Html.BeginForm())
{
//Other Html Helpers to complete the form
}

Parameters used 
  • ActionName: specify the name of action on which user will redirect
  • ControllerName: name of controller in which action has written
  • Route values: the values send as a parameter to action
  • FormMethod: Type of form whether HttpPost or HttpGet
  • Html attributes: used at run time like making readonly, applying css classes and more.

    ------------------------
Here are some standard html helpers used mostly when programming:

Understanding Attributes in Asp.Net MVC

Earlier article was about to handle browser request from the user and then invokes related controller and actions written for that particular URL. What is to be done after these requests can also be specified by the programmer in Asp.Net MVC, as this article will discuss.

Asp.Net MVC provides a way to use some extra features for actions and controller, these features are called Attributes and Filters. We have discusses about Required attribute in creating MVC View Model using required field validations.

The first and most attribute, MVC use by default is [Authorize] which specifies which action is to be executed by authenticated users only or it may be used for whole controller. The syntax for this authorize attribute is:

[Authorize]
Public ActionResult Profile()
{
return View();
}

Now whenever an un-authorized user will try to get access of this profile action, it will redirect the request to login page or the page specified.

Attributes can also take parameters specified in their declaration, they may be positional or named. Positional parameter corresponds to attribute’s public constructor like the one specified below. It will change the name of this action profile to Details, as specified as the parameter.

[ActionName(“Details”)]
Public ActionResult Profile()
{ return View(); }

Named parameter correspond to public property or field of the respective attribute. For example authorize attribute have some named parameters like order, roles and users as written in following code:

[Authorize(Roles="Role1, Role2", Users="User1, User2")]
Public ActionResult Profile()
{ return View(); }

By specifying these named parameters, this profile action will only be accessed by the users having role "Role1" and "Role2". If we talk about the users, this action will only be accessed by only the person having username "User1" and "User2".
Attribute is a class which inherits from the abstract class System.Attribure. 
So we have to inherit from the same System.Attribute class to create our own attribute. Each attribute class (created by us) will must ends with the word "Attribute". E.g.
  • AuthorizeAttribute
  • RequiredAttribute
  • ActionNameAttribute
  • CustomizedAttribute
  • ValueCheckAttribute

Sunday, May 18, 2014

Mapping Browser Request with Routing: Asp.Net MVC

An important feature, Asp.Net MVC Routing, is used for mapping incoming browser requests to particular action written in MVC Controller. By default MVC used default route table that is set up in two places i.e. Web.Config file and Global.asax file.

In application’s Web.Config file, configuration file, there are four sections related to mapping browser requests listed below. If programmer delete these sections, routing will not work for the application.

  • system.web.httpModules section
  • system.web.httpHandlers section
  • system.webserver.modules section
  • system.webserver.handlers section

Global.asax file, contains event handlers for application life cycle events, have following lines of code to be used for mapping the requests.

RouteConfig.RegisterRoutes(RouteTable.Routes);
In above line RouteConfig class have a method RegisterRoutes to define the default route table to be used to default mapping. The class having following line of code which may be changed by programmer as per requirements.

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

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

To register new route, we have to write the like as code written in RouteConfig.cs file with our new route name. The following code will create a new route with name Route1 by using the following code written in RouteConfig.cs file:

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

Now create an action in Home controller with a view having same name as below:

public ActionResult Route1()
{
return View();
}
Just run the MVC application and write only the action name in the address bar and it will show the view without any error, as shown in following image:

Mapping Browser Request with Routing: Asp.Net MVC

Tuesday, May 13, 2014

Create RadioButton list and Access Checked Value in Asp.Net MVC

List of Radio buttons are placed on the view when programmer need to checked only one value among a group by the user. Asp.Net MVC provides some simple steps to complete this task with few lines of code.

First, create an action in the controller and write a single line which will return that on the view. This type of view is called HttpGet method which only used to get the values on the page, in this case we don’t want any value from this action so we are returning only null view.

public ActionResult RadioList()
{
return View();
}

Add a view having the same name as in above action which have four radio buttons of same name and values defined sequentially, as written in below code:

<h2>RadioList</h2>
@using (Html.BeginForm())
{
    <div>
        <ul>
            <li>@Html.RadioButton("radioList", 1) RadioButton 1 </li>
            <li>@Html.RadioButton("radioList", 2) RadioButton 2 </li>
            <li>@Html.RadioButton("radioList", 3) RadioButton 3 </li>
            <li>@Html.RadioButton("radioList", 4) RadioButton 4 </li>
        </ul>

        <input type="submit" value="Submit" id="submitBtn" />
    </div>
}

All of these radio buttons have the same name “radioList” that may be changed. The last line of above code have a submit button which will submit the values of this page to the action written on the same controller and of course same name. This type of method is called HttpPost, written below:

[HttpPost]
public ActionResult RadioList(FormCollection collection)
{
ValueProviderResult result = collection.GetValue("radioList");
string checkedValue = result.AttemptedValue;
return View();
}

The parameter “collection” will have all the values input by the user on the view, now we have to access the checked value of the radiobutton list defined on the view. The class System.Web.Mvc.ValueProviderResult used to represents the result of binding a value (such as from a form post or query string) to an action-method argument property, or to the argument itself.

Create RadioButton list and Access Checked Value in Asp.Net MVC

After getting the value from the collection the checked value is stored in AttemptedValue property of this class’s object. So we have simply accessed the checked value from the view.

Sunday, April 27, 2014

How to Create CheckboxList in Asp.Net MVC

CheckboxList is used to provide some options to be select by the user. In this article we will create a list of items and then pass it to view to create a checkbox list.

Create two classes with the following format

public class CollectionVM
{
    public List<ChoiceViewModel> ChoicesVM { get; set; }
    public List<Int64> SelectedChoices { get; set; }
}

public class ChoiceViewModel
{
    public Int64 SNo { get; set; }
    public string Text { get; set; }
}

In controller’s action method write following code in which we will create a new list having some items created below. When we return this ViewModel in the view, we first set the SelectedChoices object to a new blank list of same type.

CollectionVM collectionVM = new CollectionVM();
List<ChoiceViewModel> choiceList = new List<ChoiceViewModel>();
choiceList.Add(new ChoiceViewModel() { SNo = 1, Text = "Objective Choice 1" });
choiceList.Add(new ChoiceViewModel() { SNo = 2, Text = "Objective Choice 2" });
choiceList.Add(new ChoiceViewModel() { SNo = 3, Text = "Objective Choice 3" });
choiceList.Add(new ChoiceViewModel() { SNo = 4, Text = "Objective Choice 4" });

collectionVM.ChoicesVM = choiceList;
collectionVM.SelectedChoices = new List<long>();
return View(collectionVM);

In View page start a loop to create individual checkbox and label for each item added above.

@using (Html.BeginForm())
{
    <div>
        <ul>
            @foreach (var choice in Model.ChoicesVM)
            {
                <li>
                    <input 
                                id="choice@(choice.SNo)"
                                type="checkbox" 
                                name="SelectedChoices"
                                value="@choice.SNo"
                                @(Model.SelectedChoices.Contains(choice.SNo) ? "checked" : "")/>
                    <label for="operator@(choice.SNo)">@choice.Text</label>
                </li>
            
            }
        </ul>
        <input type="submit" value="Submit" name="submitBtn" id="submitBtn" />
    </div>
}

Check out above very simple code through which we will set all the checked item's sNo in the object SelectedChoices we have sent by viewmodel. And in the second line, particular label have been designed for each checkbox.

How to Create CheckboxList in Asp.Net MVC

Now what happen when we submit this form. Write the HttpPost method of same action having this Viewmodel as parameter like:

[HttpPost]
        public ActionResult Index(CollectionVM collectionVM)
        {

This collectionVM object have all the SNo's of checked items by user. So we have created a checkbox list and then access all the checked items in our controller's action.

How to Use Multiple Models in View using ViewModel: Asp.Net MVC

Asp.Net MVC uses such type of classes in which each field may contains specific validation rules using data annotations, to let the user interact with those only. These fields may contains some extra fields to be used as a temporary purpose.

Create two classes in the Models folder named Student and Employee as written below:

public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
public class Employee
{
public int EmpId { get; set; }
public string EmpName { get; set; }
}

Create a folder in our solution named ViewModels and add a class named Student_EmployeeViewModel which will have the following code.

public class Student_EmployeeViewModel
{
public List<Student> Students { get; set; }
public List<Employee> Employees { get; set; }
}

Come to our Controller (Home controller) and add an Action (Student_Employee) which will be type of HttpGet. This action will have some lines of code as below which contains two list of student and employee and then assign them to the newly created object of Student_EmployeeViewModel.

public ActionResult Student_Employee()
{
List<Student> studentList = new List<Student>();
studentList.Add(new Student() { Name = "Student 1", Age = 24 });
studentList.Add(new Student() { Name = "Student 2", Age = 25 });
studentList.Add(new Student() { Name = "Student 3", Age = 23 });

List<Employee> empList = new List<Employee>();
empList.Add(new Employee() { EmpName = "Employee 1", EmpId = 101 });
empList.Add(new Employee() { EmpName = "Employee 2", EmpId = 102 });
empList.Add(new Employee() { EmpName = "Employee 3", EmpId = 103 });

Student_EmployeeViewModel vm = new Student_EmployeeViewModel();
vm.Students = studentList;
vm.Employees = empList;
return View(vm);
}

Create an empty view by right clicking on this action and then Add View dialog box as discussed earlier. Write the following code in this view which will have two list as defined in our ViewModel.

@model MvcApplication1.Models.Student_EmployeeViewModel

@{
    ViewBag.Title = "Student_Employee";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Students List</h2>

@foreach (var item in Model.Students)
{
    <option>@item.Name &nbsp;&nbsp; @item.Age</option>
}

<h2>Employees List</h2>

@foreach (var item in Model.Employees)
{
    <option>@item.EmpName &nbsp;&nbsp; @item.EmpId</option>
}

In the above code, we run two loops for each list of student and employee and display their name and age/id on the page.

Run this project and write the address of this action in the address bar, this will shows all the data of student as well as employees we have added in the action.

How to Use Multiple Models in View using ViewModel: Asp.Net MVC

Tuesday, April 22, 2014

How to Create DropDownList in Asp.Net MVC

Drop down list is a common and usable control in every programming area to let the user can select only one item from the list. In MVC we have to create a list in action method of controller and then pass it through any method like ViewBag and ViewModel etc.

Programmer can create required type of list as per the requirements, we will create a SelectListItem type of list because this list provides two property Text and Value by default. Create a simple list of type SelectListItem and add some items (we have added four item here) as added below:

List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Value 1", Value = "1" });
items.Add(new SelectListItem { Text = "Value 2", Value = "2" });
items.Add(new SelectListItem { Text = "Value 3", Value = "3" });
items.Add(new SelectListItem { Text = "Other", Value = "4" });

Now to pass this to View page write a single line as written below:

ViewBag.ddlItems = new SelectList(items, "Value", "Text");

Value will be the dataValue field and Text will be dataText field for this dropdownlist. In the view page create a form and of course a dropdownlist with a submit button:

@using (Html.BeginForm())
{
    <div>
        @Html.DropDownList("selectedItem", (IEnumerable<SelectListItem>)ViewBag.ddlItems)
        <input type="submit" value="Submit" id="submitBtn" />
    </div>
}

First parameters of this helper Html.DropDownList() specifies name of the HTML select element, and also the name of the view model property that is bound to the element. Second parameter shows the list of options of select list.

This will create a dropdownlist with a submit button. Run the application and open particular view in the browser. Select any value and then submit. Oops! i haven't write the code to access the selected value. So write HttpPost type of action:

public ActionResult Index(string selectedItem)
{
....
....

Here parameter selectedItem is the same name of dropdownlist we have assigned in the view page. Again run the application, select any value("Value 2") and then submit. This parameter will contain the selected value(2).

© Copyright 2013 Computer Programming | All Right Reserved