-->

Tuesday, May 27, 2014

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

Saturday, April 19, 2014

How to Validate File or File type in Java Script MVC

Programmer need to check whether the file is selected by the user or not, when uploading a file. If user will not upload any file and submit the form, the code will throw an exception with description like "file must not be null".

To overcome this issue programmer have to check the uploaded file before the form submission, and this can be performed by using Java script. Write the following code in our view where the file upload control is placed:

function validateForm() {
if ($("#file").val() == "") {
alert("Please select a file");
return false;
}
}

Here “#file” is the id of file upload control and we are checking the value of this control. If the value is empty then it will alert with the message shown and return back to the form. If this control will have file then it will submit the form. On the submit button, just call this function to execute this code with Onclick=”validateForm();”.

Now to select only some file types write another function as below:

function checkfile(sender) {
        var validExts = new Array(".jpeg", ".jpg", ".png");
        var fileExt = sender.value;
        fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
        if (validExts.indexOf(fileExt) < 0) {
            alert("File must of types \".jpeg\", \".jpg\", \".png\");
            $("#file").val('');
            return false;
        }
        else return true;
    }

This function will be called on OnChange event of the file upload control. It will show an alert message written above if the type of selected file will not be in the list declared in the function. Write CheckFile(this) in onChange event of the file upload control.

In this function we are checking only the extension of the selected file, extension may be found by any individual logic. Earlier article was about to uploading file, this java script will not submit the form if user will not select any file through the file upload control.

Monday, April 14, 2014

How to Use ViewModel in Asp.Net MVC

ViewModel is used to specify the fields which may be required in create, edit or list the data on a strongly typed view. Asp.Net MVC uses these type of classes in which each field may contains specific validation rules using data annotations. These validation rules may be used for any type of data like DateTime, String or Integer.

Basically, Models are used to create database in Entity Framework and may be used to access database using the same name of classes. To differentiate the model with views programmer have to use ViewModel to interact view to make them strongly typed.

According to our previous article, Student Model have a list of field i.e. Id (primary key), name, age and city. In a view, we want to show only name and city then we have to create a view model with only these two fields and some validation rules like written below:

public class StudentViewModel
{
[Display(Name="Student Name")]
[Required(ErrorMessage="Name Required")]
public string Name { get; set; }

[Display(Name = "Student City")]
[Required(ErrorMessage = "City Required")]
public string City { get; set; }
}
Open our controller and write an action type of HttpGet with some line of code to return just a blank view model of type StudentViewModel.
public ActionResult StudentVM()
{
StudentViewModel svm = new StudentViewModel();
return View(svm);
}
Add a strongly typed view to select particular options listed in the below image:

How to Use ViewModel in Asp.Net MVC

The view page which is automatically creates as strongly typed, when run in the browser, have the display name for each field set in the ViewModel. When create button is clicked without any value, both of them show the error messages assigned previously in the ViewModel.

How to Use ViewModel in Asp.Net MVC

So ViewModels are used to organize and manage data in strongly typed view with more flexible way than other complex ways like Models or ViewBag etc.

Monday, March 31, 2014

How to Implement Server Side Validation in Asp.Net MVC

Server side validation can be performed by submitting the model and then check the values in related action of the controller. Asp.Net MVC framework populates a ModelState object with any validation failure and passes that object to controller. If any error found just add the error in the state of model by using ModelState object of type ModelStateDictionary.

According to our previous article about client side validation, programmer have to change some minor changes in the view as well as controller’s action. Just write the following code in our GetValues view:

@using (Html.BeginForm())
{
    <div>
        <div>Name: </div>
        <div>
            @Html.TextBox("username")
            @Html.ValidationMessage("nameError")
        </div>
        <input type="submit" value="Send" />
    </div>
}

Here I have added a validation message having the key "nameError" to show the validation message for username. The message passed with this key will be shown through this line of code. Programmer have to change the action code according to this view code and it should be look like:

[HttpPost]
public ActionResult GetValues(string username)
{
if (username == string.Empty)
{
ModelState.AddModelError("nameError", "Name must not be empty");
}
return View();
}

As you can see the condition I have placed that it will only check whether the textbox is empty. If username will be passed empty then it will just add an error message having the same key written in the view code, by using the code written in if block.

Run the MVC application the leave black the textbox, click on send button. It will go to the action, check the condition and then return the view after adding the error. The page will be look like:

How to Implement Server Side Validation in Asp.Net MVC

So this is how to perform server side validation and client side validation in MVC. In further articles we will understand more about these.

Thursday, March 27, 2014

How to Implement Client-Side Validation in ASP.NET MVC

Implementing Client-Side Validation in an Asp.Net MVC application requires some app settings in the web.config file that must be true. These settings are used to enable two jquery i.e. jquery.validate.min.js and jquery.validate.unobtrusive.min.js in our project.

<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

These setting are by default enabled in an MVC project so programmer just remember to check these lines if validation are not working at all. In Visual studio there is an in-built validation attribute mostly used in all the required fields.

[Required]
(Field to be required…..)

This attribute is defined in System.ComponentModel.DataAnnotations namespace and it is used to not complete the page submission if user don’t enter any value in the respective field. The error message shown is the standard message ("Required") by default, it can be changed by the programmer by using:

[Required (ErrorMessage = "This field is Required ")]
(Field to be required…..)

After doing the changes in model, in view page programmer have to write the element which shows the error for that specified field.

(Field to be entered)
@Html.ValidationMessageFor("the labda expression for the property")

Some more lines are used by Visual Studio to adds these references automatically on view. It adds following code snippet to the bottom of the view:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Run the respected view, don’t insert any value, click on submit then it will show the specified error without submitting the page. This is client validation, when this page submitted and then show errors, it will called server side validation discussed in the next article.

Sunday, August 18, 2013

Restrict users from Entering in TextBox

Masked textbox supports a declarative syntax for accepting or rejecting user input. Masked textbox may be used to specify input characters, input position in the mask, mask literals and some more operations can also be done using masked textbox without any custom validation logic.

Textbox is used to allow the user to input text information to be used by the programmer. To use our custom logic we can restrict numbers/characters to be inputted by the user. We can restrict any key to be inputted by the user.

Textbox’s Key Press event occurs when the control has focus and user press and releases a key. It has following format that is in C# language:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
}

The parameter e provides the data for this event which is of type KeyPressEventArgs. Char class has some in-built functions for checking the pressed and released key by user.

char.IsDigit(): whether the character is decimal digit or not.
char.IsLetter(): whether the character is a letter.
Char.IsLetterOrDigit(): whether the character is letter or digit.

There are many more method to check each type of data, we can read more here.
To restrict the user from entering the digit in textbox
if (char.IsDigit(e.KeyChar))
e.Handled = true;

Here e.Handled will tell the debugger that I have handled this event. We can use desired method to prevent specified type of key by the user.

To restrict both the letter and digit to be inputted by the user in c# language:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsLetterOrDigit(e.KeyChar) || char.IsDigit(e.KeyChar))
e.Handled = true;
}

Now when we run this form and try to enter anything between a-z, A-Z and 0-9, we can’t enter anything among these values.
© Copyright 2013 Computer Programming | All Right Reserved