Friday, December 5, 2014

asp.net mvc validations using dataannotations

hi lets see how to do validation in asp.net mvc using dataannotations
so lets start implementing this.

1. first create a model :
public class DataForm
{
[Key]
public int EMPID { get; set; }
[StringLength(60, MinimumLength = 3,ErrorMessage=”Min String length is 3″)]
public string EMPNAME { get; set; }
[Required(ErrorMessage=”Field should not be empty”)]
public string EMPADD { get; set; }
[RegularExpression(@”^[0-9]{0,8}$”, ErrorMessage = “Salary should be Numeric”)]
public string EMPSAL { get; set; }
}
here in the above model we will define the form fields and the validation messages. we also need to add below namespace
using System.ComponentModel.DataAnnotations;
_1


2. after this go to controller and add two action methods.
httppost action method will only accept the postback requests like the submit, create.
public ActionResult data() // will be called intially
{
return View();
}
[HttpPost]
public ActionResult data(DataForm d1) // will handle postback requests
{
if (ModelState.IsValid)
{
return RedirectToAction(“saveData”);
}
return View(d1);
}

_2
3. now add a strongly typed view using model DataForm and using scaffold template as create.

1
@model mvcFilters.DataForm
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>data</title>
</head>
<body>
<script src=”~/Scripts/jquery-1.8.2.min.js”></script>
<script src=”~/Scripts/jquery.validate.min.js”></script>
<script src=”~/Scripts/jquery.validate.unobtrusive.min.js”></script>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>DataForm</legend>
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPNAME)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPNAME)
@Html.ValidationMessageFor(model => model.EMPNAME)
</div>
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPADD)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPADD)
@Html.ValidationMessageFor(model => model.EMPADD)
</div>
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPSAL)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPSAL)
@Html.ValidationMessageFor(model => model.EMPSAL)
</div>
<p>
<input type=”submit” value=”Create” />
</p>
</fieldset>
}
<div>
@Html.ActionLink(“Back to List”, “Index”)
</div>
</body>
</html>
now run the project to check if the validations are working properly.
output:
2

Exception handling in asp.net mvc using HandleError Attribute

hi in this post i will show how to use handleError attribute for exception handling in asp.net mvc.

we can add handleError attribute around the whole controller class or just around the individual action methods.
1
next we need to add
<customErrors mode=”On”></customErrors> 
in the webconfig file.
10-25-2014 8-51-02 PM

Now in the view folder we will create a shared folder and in that we will add a view page called error.cshtml
so whenever there is any exception it will get redirected to this page.
we will create a strongly typed view which will have model HandleErrorInfo
error.cshtml code:
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>error</title>
</head>
<body>
<div>
Error Occured !!!
<table border=”1″>
<tr>
<td>
Controller Name: @Model.ControllerName
</td>
<td>
Action Name: @Model.ActionName
</td>
<td>
Exception Details: @Model.Exception
</td>
</tr>
</table>
</div>
</body>
</html>
model HandleErrorInfo code :
public class HandleErrorInfo
{
public string ActionName { get; set; }
public string ControllerName { get; set; }
public Exception Exception { get; set; }
}

Output:
Now run the application
error

Implementing Asp.net Custom MVC filters [Part 2]

hi in this post i will show an another way implementing custom asp.net mvc filters.
Now i will create separate class for every filter types which will inherit attributes according to type and then we will implement that inherited methods.
here we will use the name of filter class and add it on the top of action method or we can also add it to the whole controller.
Code :
1
Controller :
[CustomAuthorization]
public class MainController : Controller
{
//
// GET: /Main/
[CustomAction]
[CustomExceptionFilter]
public ActionResult Index()
{
int i = Convert.ToInt32(“1″) / Convert.ToInt32(“0″);
ViewBag.message = “hello world”;
return View();
}
}
class CustomAuthorization : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
filterContext.Controller.ViewBag.AuthorizationMsg = “From OnAuthorization method”;
}
}
class CustomAction : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.ViewBag.ActionExecutingMsg = “From OnActionExecuting method”;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.Controller.ViewBag.ActionExecutedMsg = “From OnActionExecuted method”;
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.Controller.ViewBag.ResultExecutingMsg = “From OnResultExecuting method”;
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.Controller.ViewBag.ResultExecutedMsg = “From OnResultExecuted method”;
}
}
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new ViewResult
{
ViewName = “error”,
};
}
}
View:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>Index</title>
</head>
<body>
<div>
@ViewBag.message
<br />
@ViewBag.AuthorizationMsg
<br />
@ViewBag.ActionExecutingMsg
<br />
@ViewBag.ActionExecutedMsg
<br />
@ViewBag.ResultExecutingMsg
<br />
@ViewBag.ResultExecutedMsg
<br />
@ViewBag.ExceptionMsg
</div>
</body>
</html>

I’m adding one more view named error.cshtml , to which we will redirect when any exception occurs.
2



Output:
1. Without Exception
1
2. With Exception
2

Implementing Asp.net Custom MVC filters [Part 1]

hi lets implement asp.net mvc filters
Filters help us to add logic before and after a controller action which is getting called. (Like we need to log something when controller action is called)
types of filters in asp.net mvc :
1. Authorization filter
2. Action filter
3. result filter (viewresult, jsonresult etc.)
4. exception filter

example:
create a new asp.net mvc empty project. Now i will add a new controller and will return a string to the view using viewbag.
Now for implementing Custom MVC filters, we will implement methods from IAuthorizationFilter,IActionFilter,IResultFilter,IExceptionFilter
interface.

1
controller code 
public class MainController : Controller,IAuthorizationFilter,IActionFilter,IResultFilter,IExceptionFilter
{
//
// GET: /Main/
public ActionResult Index()
{
ViewBag.message = “hello world”;
return View();
}
protected override void OnAuthorization(AuthorizationContext filterContext)
{
ViewBag.AuthorizationMsg = “From OnAuthorization method”;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
ViewBag.ActionExecutingMsg = “From OnActionExecuting method”;
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
ViewBag.ActionExecutedMsg = “From OnActionExecuted method”;
}
protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
ViewBag.ResultExecutingMsg = “From OnResultExecuting method”;
}
protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
ViewBag.ResultExecutedMsg = “From OnResultExecuted method”;
}
protected override void OnException(ExceptionContext filterContext)
{
ViewBag.ExceptionMsg = “From OnException method”;
}
}
View code
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>Index</title>
</head>
<body>
<div>
@ViewBag.message
<br />
@ViewBag.AuthorizationMsg
<br />
@ViewBag.ActionExecutingMsg
<br />
@ViewBag.ActionExecutedMsg
<br />
@ViewBag.ResultExecutingMsg
<br />
@ViewBag.ResultExecutedMsg
<br />
@ViewBag.ExceptionMsg
</div>
</body>
</html>

Output :
Below is the sequence of execution of the methods:
2
As View gets rendered before OnResultExecuted method , we are not able to see the onresultexecuted viewbag message.
OnException method will get called when there is any exception.

Getting started with AngularJS

hi lets get started with angular js
Angular js was built using the Javascript. It lets us extends Html with ng-directives i.e. ng-app, ng-model, ng-bind.

Lets see this below Example:
<body>
<h4>Welcome to Angular JS Tutorials</h4>
<div ng-app=”myFirstApp” ng-controller=”nameController”>
Enter Name: <input type=”text” ng-model=”myName”><br>
Full Name: {{myName}}
</div>
<script>
angular.module(‘myFirstApp’, []).
controller(‘nameController’, function nameController($scope) {
$scope.myName = “XYZ”;
});
</script>
</body>
</html>
Here in this example as soon as a new text is updated it gets updated below in the view , so basically it means that whenever there is any change in model it will automatically get reflected in view.
1

This is one the important features of AngularJS as it synchronizes data between model and view, which means two way data binding.