Showing posts with label MVC3. Show all posts
Showing posts with label MVC3. Show all posts

Saturday, September 15, 2012

MVC 3 Reload Partial View with Validations

 $('#partialcontroldiv').load('@Url.Content("~/ControlerName/ActionName")?id=' + id, '', function () {               
              //below lines to reapply dataannotation validation on partial view
                $('form').removeData("validator");
                $("form").removeData("unobtrusiveValidation");
                $.validator.unobtrusive.parse(document);


            });
Read More

MVC 3: Generate Textbox or labels in Foreach Loop

@foreach (var item in Model )
{







@Html.LabelFor(a=> item.ItemName)



@Html.LabelFor(a => item.Description)




@Html.LabelFor(a => item.Qty)



@Html.TextBoxFor(a => item.Price)





}
Read More

MVC 3: Cross Site Request Forgery protection

write @Html.AntiForgeryToken() in view to generate any forgery token (hidden textbox)
and use [ValidateAntiForgeryToken] on action to validate that request has valid anti forgery token
Read More

Change value of RequiresQuestionAndAnswer in ASP.NET Membership provider

MembershipUser user = Membership.GetUser();
string newPassword = "newPass";
string tempPassword = string.Empty;
if (Membership.Provider.RequiresQuestionAndAnswer)
{
var _requiresQA = Membership.Provider.GetType().GetField("_RequiresQuestionAndAnswer",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
//change the value in the private field
_requiresQA.SetValue(Membership.Provider, false);
//do the reset
tempPassword = user.ResetPassword();
//set it's original value
_requiresQA.SetValue(Membership.Provider, true);
}
else
{
tempPassword = user.ResetPassword();
}

http://djsolid.net/blog/asp.net-membership---change-password-without-asking-the-old-with-question-and-answer
Read More

Authorization and Permission using Attribute in MVC3

Public enum PermissionType
{
permission1,
permission2,
permissiontype3
}
public class AuthorizePermissionAttribute : AuthorizeAttribute
{
private readonly IRolesService _rolesService;
private readonly IUserService _userService;
private string[] _rolesSplit;
private string[] _usersSplit;
public PermissionType[] PermissionName;
public AuthorizePermissionAttribute()
: this(new AspNetMembershipProviderWrapper(), new AspNetRoleProviderWrapper())
{
}
public AuthorizePermissionAttribute(IUserService userService, IRolesService rolesService)
{
_userService = userService;
_rolesService = rolesService;
}
public AuthorizePermissionAttribute(PermissionType[] PermissionName)
: this(new AspNetMembershipProviderWrapper(), new AspNetRoleProviderWrapper())
{
this.PermissionName = PermissionName;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
try
{

var user = httpContext.User;
if (!user.Identity.IsAuthenticated)
return false;

if (_usersSplit == null)
_usersSplit = SplitString(Users);
if (_rolesSplit == null)
_rolesSplit = SplitString(Roles);

if (_usersSplit.Any() && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
return false;

//if (!_rolesService.Enabled || !_rolesSplit.Any())
// return true;

//return _rolesSplit.Any(user.IsInRole);

IEnumerable userroles = _rolesService.FindByUser(MySession.Current.User);


var roleids = _context.aspnet_Roles.Where(a => userroles.Contains(a.RoleName)).Select(a => a.RoleId);
var rpt = _context.Role_Permission_Trans.Where(a => roleids.Contains(a.RoleID)).Select(a => a.PID);
var pm = _context.PermissionMasters.Where(p => rpt.Contains(p.PID));
var permissions = PermissionName.ToString(",").ToLower().Split(",".ToCharArray());
var res = pm.Where(p => permissions.Contains(p.PermissionName.ToLower()));
if (res.IsNotNull() && res.Count() > 0)
{
return true;
}
else
{
return false;
}

}
catch (Exception)
{


}
return false;
//return base.AuthorizeCore(httpContext);

}
private static string[] SplitString(string original)
{
if (String.IsNullOrEmpty(original))
return new string[0];

var split = from piece in original.Split(',')
let trimmed = piece.Trim()
where !String.IsNullOrEmpty(trimmed)
select trimmed;
return split.ToArray();
}
}

public class LogonAuthorize : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!(filterContext.Controller is AccountController) && !(filterContext.Controller is HomeController))
base.OnAuthorization(filterContext);
}
}
Read More

Tuesday, April 3, 2012

Using JQGrid in ASP.NET MVC 3

JQGrid is one of the most powerful opensource grid available for commercial use.

We can easily use JQGrid in MVC 3 also, but instead of directly using JQGrid, i would like to refer to use any component/wrapper built over JQGrid, which can make data and grid structure in strongly typed form.

After lots of search i found a very good helper Lib.Web.MVC, it is a library which contains some helper classes for ASP.NET MVC such as strongly typed jqGrid helper, XSL transformation HtmlHelper/ActionResult, custom attributes and more.

Now lets use this "Lib.Web.MVC" and create an application.

Now lets say i wants to create an application which is showing employee details in grid using JQGrid (Lib.Web.MVC).


First of all add Lib.Web.MVC to you project either using NuGet or directly download the dll/application from Lib.Web.MVC.

Now next step is to create an ViewModel class for Grid, in which we creates properties for all the column (of employee) which we wants to show in grid and add various attributes on it.

like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using DataAnnotationsExtensions;
using Lib.Web.Mvc.JQuery.JqGrid.DataAnnotations;
using System.Web.Mvc;
//your project namespace will be here.
 public class EmployeeDetailViewModel
    {

        [JqGridColumnLayout(Width = 40)]//fix the width of column in grid
        [JqGridColumnLabel(Label = "")] // to show select all column with check box
        public string All { get; set; }

        [ScaffoldColumn(false)]//if you don't wants to show this column in grid
        public Guid ProfileID { get; set; }

        [StringLength(20)]
        [Display(Name = "Employee Id")]// heading of columns
        public string EmployeeId { get; set; }

        [StringLength(100)]
        [Display(Name = "Employee Name")]
        public string EmployeeName { get; set; }

        [Display(Name = "Email Address")]
        [Required, Email] // this will be used when same model will be used to take value for create employee
        public string Email { get; set; }

        [StringLength(50)]
        [Display(Name = "Address")]
        public string Address { get; set; }

        [JqGridColumnLayout(Width = 150)]
        public string Action { get; set; }

        public EmployeeDetailViewModel()
        {

        }

        public EmployeeDetailViewModel(MyNamespace.Models.EmployeeProfile profile)
        {
            All = "";
            ProfileID = profile.PID;
            EmployeeId = profile.EmployeeId;
            EmployeeName = profile.EmployeeName;
            Email = profile.Email;
            Address = profile.Address;

//the action column will contains "Edit" and "View" links in grid.
            Action = "" +
"";

        }

    }


 public class Mylib 
    {
        public static System.Web.Mvc.UrlHelper GetURLHelper()//to get the action url
        {
            return new UrlHelper(HttpContext.Current.Request.RequestContext);
        }
}


in view create jqgrid like:
@{ 
   int noofrows = Convert.ToInt32( System.Configuration.ConfigurationManager.AppSettings["RowsInGrid"].ToString());//to get rows per page

   var grid = new Lib.Web.Mvc.JQuery.JqGrid.JqGridHelper("EmpGrid",
      dataType: Lib.Web.Mvc.JQuery.JqGrid.JqGridDataTypes.Json,
      methodType: Lib.Web.Mvc.JQuery.JqGrid.JqGridMethodTypes.Post,
      pager: true,
      rowsNumber: noofrows,
      url: Url.Action("GetEmployee"),//this action will be called to get data 
      viewRecords: true,
      autoWidth: true// to fit the grid in parent div/table
  );
  }

 [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetEmployee(JqGridRequest request, EmployeeViewModel viewModel)
        {

   int totalPagesCount =0;
                        var employees = _empRepo.FindRange(pageIndex: request.PageIndex, pageLength: request.RecordsCount, out totalPagesCount);

                       
                        JqGridResponse response = new JqGridResponse()
                        {
                            TotalPagesCount = (int)Math.Ceiling((float)totalPagesCount / (float)request.RecordsCount),
                            PageIndex = request.PageIndex,
                            TotalRecordsCount = totalRecordsCount
                        };

                        response.Records.AddRange(from i in employees select new JqGridRecord(Convert.ToString(new EmployeeViewModel(i).employeeid), new EmployeeViewModel(i)));

                        return new JqGridJsonResult() { Data = response };
         }



Compiled By: Rajesh Rolen

Read More

Wednesday, January 25, 2012

Setup ASP.NET MVC3 on IIS 5

These are steps to setup MVC3 project on IIS 5 1. Right click on Default Web Site and click Properties
2. Make sure the website or virtual directory is an Application.
3. Set permissions to Scripts Only
4. Click Configuration. Under the Mappings tab, click the Add button
5. You need to insert the path to the file aspnet_isapi.dll. This is most likely C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll.
6. In the Extension field, enter “.*” (excluding quotes).
7. Select All Verbs. Select “Script Engine”. Make sure ”Check that file exists” is not selected.
8. Here’s the bug. “.*” This isn’t a valid extension in IIS 5.1 so the OK button is disabled. Click in the
Extension field, then in the Executable field, and the OK button should be enabled! Click OK at this point.

Compiled By: Rajesh Rolen

Read More

Monday, December 19, 2011

Differnce Between Actionresult and VewResult in ASP.NET MVC

ActionResult is an abstract class means ViewResult derives from ActionResult. You declare it this way so you can take advantage of polymorphism and return different types in the same method.

Eg:
public ActionResult Foo()
{
   if (someCondition)
     return View(); // returns ViewResult
   else
     return Json(); // returns JsonResult
}
I above example the return type of Foo() is "ActionResult" so now i am not bound to return a specific type of value, i can return a View/Json/PartialView/RedirectResult. If i would have used "ViewResult" then i would be able to return "View" only. So ActionResult provides us facility to take advantage of polimorphism in Type of return.

ActionResult have several subtypes:

a) ViewResult - Renders a specifed view to the response stream

b) PartialViewResult - Renders a specifed partial view to the response stream

c) EmptyResult - An empty response is returned

d) RedirectResult - Performs an HTTP redirection to a specifed URL

e) RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data

f) JsonResult - Serializes a given ViewData object to JSON format

g) JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client

h) ContentResult - Writes content to the response stream without requiring a view

i) FileContentResult - Returns a fle to the client

j) FileStreamResult - Returns a fle to the client, which is provided by a Stream

k) FilePathResult - Returns a fle to the client

Compiled By: Rajesh Rolen

Read More
Powered By Blogger · Designed By Seo Blogger Templates