Monday 31 July 2017

Bypass the Internet Explorer 10 requirement for Visual Studio 2013

Since the release of Visual Studio 2013 there have been some complains about one of the requirements in particular. Some versions of Visual Studio 2013 require Internet Explorer 10 to be installed or else the installation refuses to continue. For users that for some reasons they can’t, or simply don’t want to install Internet Explorer 10 on their system this might pose a big problem as they won’t be able to upgrade to the latest version of Visual Studio.
Luckily a user managed to find a workaround that can be used till Microsoft manages to find a way to remove this requirement. The workaround basically tricks the installer into thinking that you already have Internet Explorer 10 installed on your system, therefore allowing the installer to resume the installation.
Simply paste the following lines in a file and save it as .bat. Then simply run it. After that the registry entries should be modified and you can continue the installation of Visual Studio 2013 as you normally would, this time without the Internet Explorer 10 requirement error.
Note that since this alters the registry entries under HKEY_LOCAL_MACHINE you might need administration rights. So make sure that the .bat file you created is run as admin.

Saturday 29 July 2017

Model Binding

In this section, you will learn about model binding in MVC framework.
To understand the model binding in MVC, first let's see how you can get the http request values in the action method using traditional ASP.NET style. The following figure shows how you can get the values from HttpGET and HttpPOST request by using the Request object directly in the action method.
Accessing Request Data
As you can see in the above figure, we use the Request.QueryString and Request (Request.Form) object to get the value from HttpGet and HttpPOST request. Accessing request values using the Request object is a cumbersome and time wasting activity.
With model binding, MVC framework converts the http request values (from query string or form collection) to action method parameters. These parameters can be of primitive type or complex type.

Binding to Primitive type:

HttpGET request embeds data into a query string. MVC framework automatically converts a query string to the action method parameters. For example, the query string "id" in the following GET request would automatically be mapped to the id parameter of the Edit() action method.
Model Binding

This binding is case insensitive. So "id" parameter can be "ID" or "Id".
You can also have multiple parameters in the action method with different data types. Query string values will be converted into paramters based on matching name.
For example, http://localhost/Student/Edit?id=1&name=John would map to id and name parameter of the following Edit action method.
Example: Convert QueryString to Action Method Parameters

public ActionResult Edit(int id, string name)
{            
    // do something here
            
    return View();
}

Binding to Complex type:

Model binding also works on complex types. Model binding in MVC framework automatically converts form field data of HttpPOST request to the properties of a complex type parameter of an action method.
Consider the following model classes.
Model classes - C#:

public class Student
{
    public int StudentId { get; set; }
    [Display(Name="Name")]
    public string StudentName { get; set; }
    public int Age { get; set; }
    public Standard standard { get; set; }
}

public class Standard
{
    public int StandardId { get; set; }
    public string StandardName { get; set; }
}

Now, you can create an action method which includes Student type parameter. In the following example, Edit action method (HttpPost) includes Student type parameter.
Example: Action method with complex type parameter


[HttpPost]
public ActionResult Edit(Student std)
{
    var id = std.StudentId;
    var name = std.StudentName;
    var age = std.Age;
    var standardName = std.standard.StandardName;

    //update database here..

    return RedirectToAction("Index");
}

So now, MVC framework will automatically maps Form collection values to Student type parameter when the form submits http POST request to Edit action method as shown below.
Model Binding
So thus, it automatically binds form fields to the complex type parameter of action method.

FormCollection:

You can also include FormCollection type parameter in the action method instead of complex type, to retrieve all the values from view form fields as shown below.
Model Binding

Bind Attribute:

ASP.NET MVC framework also enables you to specify which properties of a model class you want to bind. The [Bind] attribute will let you specify the exact properties a model binder should include or exclude in binding.
In the following example, Edit action method will only bind StudentId and StudentName property of a Student model.
Bind example:

[HttpPost]
public ActionResult Edit([Bind(Include = "StudentId, StudentName")] Student std)
{
    var name = std.StudentName;
           
    //write code to update student 
            
    return RedirectToAction("Index");
}

You can also use Exclude properties as below.
Bind example:

[HttpPost]
public ActionResult Edit([Bind(Exclude = "Age")] Student std)
{
    var name = std.StudentName;
           
    //write code to update student 
            
    return RedirectToAction("Index");
}

The Bind attribute will improve the performance by only bind properties which you needed.

Inside Model Binding:

As you have seen that Model binding automatically converts request values into a primitive or complex type object. Model binding is a two step process. First, it collects values from the incoming http request and second, populates primitive type or complex type with these values.
Value providers are responsible for collecting values from request and Model Binders are responsible for populating values.
Model Binding in MVC
Default value provider collection evaluates values from the following sources:
  1. Previously bound action parameters, when the action is a child action
  2. Form fields (Request.Form)
  3. The property values in the JSON Request body (Request.InputStream), but only when the request is an AJAX request
  4. Route data (RouteData.Values)
  5. Querystring parameters (Request.QueryString)
  6. Posted files (Request.Files)
MVC includes DefaultModelBinder class which effectively binds most of the model types

HtmlHelper.Editor

We have seen different HtmlHelper methods used to generated different html elements in the previous sections. ASP.NET MVC also includes a method that generates html input elements based on the datatype. Editor() or EditorFor() extension method generates html elements based on the data type of the model object's property.
The following table list the html element created for each data type by Editor() or EditorFor() method.
Property DataTypeHtml Element
string<input type="text" >
int<input type="number" >
decimal, float<input type="text" >
boolean<input type="checkbox" >
Enum<input type="text" >
DateTime<input type="datetime" >
We will use the following model class with Editor and EditorFor method.
Example: Student Model

public class Student
{
    public int StudentId { get; set; }
    [Display(Name="Name")]
    public string StudentName { get; set; }
    public int Age { get; set; }
    public bool isNewlyEnrolled { get; set; }
    public string Password { get; set; }
    public DateTime DoB { get; set; }
}

Editor():

Editor() method requires a string expression parameter to specify the property name. It creats a html element based on the datatype of the specified property.
Editor() signature: MvcHtmlString Editor(string propertyname)
Visit MSDN to know all the overloads of Editor() method
Consider the following example to understand the Editor() method.
Example: Editor() in Razor view

StudentId:      @Html.Editor("StudentId")
Student Name:   @Html.Editor("StudentName")
Age:            @Html.Editor("Age")
Password:       @Html.Editor("Password")
isNewlyEnrolled: @Html.Editor("isNewlyEnrolled")
Gender:         @Html.Editor("Gender")
DoB:            @Html.Editor("DoB")


Output of Editor() and EditorFor() method
In the above example, we have specified property names of Student model as a string. So, Editor() method created the appropriate input elements based on the datatype as shown in the above figure.

EditorFor:

EditorFor() method is a strongly typed method. It requires the lambda expression to specify a property of the model object.
EditorFor() signature: MvcHtmlString EditorFor(<Expression<Func<TModel,TValue>> expression)
Visit MSDN to know all the overloads of EditorFor() method
Example: EditorFor() in Razor view

StudentId:      @Html.EditorFor(m => m.StudentId)
Student Name:   @Html.EditorFor(m => m.StudentName)
Age:            @Html.EditorFor(m => m.Age)
Password:       @Html.EditorFor(m => m.Password)
isNewlyEnrolled: @Html.EditorFor(m => m.isNewlyEnrolled)
Gender:         @Html.EditorFor(m => m.Gender)
DoB:            @Html.EditorFor(m => m.DoB)


Output of Editor() and EditorFor() method
In the above example of EditorFor() method, we have specified the property name using the lambda expression. The result would be the same as the Editor() method as shown in the above figure.

Create TextBox using HtmlHelper

Learn how to generate textbox control using HtmlHelper in razor view in this section.
HtmlHelper class includes two extension methods which creates a textbox (<input type="text">) element in razor view: TextBox() and TextBoxFor(). The TextBox() method is loosely typed method whereas TextBoxFor() is a strongly typed method.
We will use following Student model with TextBox() and TextBoxFor() method.
Example: Student Model

public class Student
{
    public int StudentId { get; set; }
    [Display(Name="Name")]
    public string StudentName { get; set; }
    public int Age { get; set; }
    public bool isNewlyEnrolled { get; set; }
    public string Password { get; set; }
}

TextBox():

The Html.TextBox() method creates <input type="text" > element with specified name, value and html attributes.

TextBox() method signature:

MvcHtmlString Html.TextBox(string name, string value, object htmlAttributes)
TextBox method has many overloads. Please visit MSDN to know all the overloads of TextBox() method.
The TextBox() method is a loosely typed method because name parameter is a string. The name parameter can be a property name of model object. It binds specified property with textbox. So it automatically displays a value of the model property in a textbox and visa-versa.
Example: Html.TextBox() in Razor View

@model Student

@Html.TextBox("StudentName", null, new { @class = "form-control" })  

Html Result:

<input class="form-control" 
        id="StudentName" 
        name="StudentName" 
        type="text" 
        value="" />

In the above example, the first parameter is "StudentName" property of Student model class which will be set as a name & id of textbox. The second parameter is a value to display in a textbox, which is null in the above example because TextBox() method will automatically display a value of the StudentName property in the textbox. The third parameter will be set as class attribute. HtmlAttributes parameter is an object type, so it can be anonymous object and attributes name will be its properties starting with @ symbol.
You can also specify any name for the textbox. However, it will not be bind to a model.
Example: Html.TextBox() in Razor View

@Html.TextBox("myTextBox", "This is value", new { @class = "form-control" })  

Html Result:

<input class="form-control" 
        id="myTextBox" 
        name="myTextBox" 
        type="text" 
        value="This is value" />


Output in the browser
Output of TextBox() Html Helper method

TextBoxFor:

TextBoxFor helper method is a strongly typed extension method. It generates a text input element for the model property specified using a lambda expression. TextBoxFor method binds a specified model object property to input text. So it automatically displays a value of the model property in a textbox and visa-versa.

TextBoxFor() method Signature:

MvcHtmlString TextBoxFor(Expression<Func<TModel,TValue>> expression, object htmlAttributes)
Visit MSDN to know all the overloads of TextBoxFor() method.
Example: TextBoxFor() in Razor View

@model Student

@Html.TextBoxFor(m => m.StudentName, new { @class = "form-control" })  

Html Result:

<input class="form-control" 
        id="StudentName" 
        name="StudentName" 
        type="text" 
        value="John" />

In the above example, the first parameter in TextBoxFor() method is a lambda expression which specifies StudentName property to bind with the textbox. It generates an input text element with id & name set to property name. The value attribute will be set to the value of a StudentName property e.g John. The following figure shows the input text element genered by above example.
Output of TextBoxFor() Html Helper method

Difference between TextBox and TextBoxFor:

  • @Html.TextBox() is loosely typed method whereas @Html.TextBoxFor() is a strongly typed (generic) extension method.
  • TextBox() requires property name as string parameter where as TextBoxFor() requires lambda expression as a parameter.
  • TextBox doesn't give you compile time error if you have specified wrong property name. It will throw run time exception.
  • TextBoxFor is generic method so it will give you compile time error if you have specified wrong property name or property name changes. (Provided view is not compile at run time. )

Recent Post

Parallel Task in .Net 4.0