Thursday, November 22, 2018

Specified argument was out of the range of valid values. Parameter name: site

Specified argument was out of the range of valid values. Parameter name: site

While development many time we face this issue.It come generally when we change pc or laptop ,we just install visual studio and sql server and start our project.We forget to enable IIS setting so this error comes.
Solution : 
Please open 
 Control Panel -> Programs -> Programs and Features -> Turn Windows features on or off -> Internet Information Services and check the Internet Information Service if unchecked.

Image for reference :

Monday, November 19, 2018

Action Filters in asp.net MVC

What are Action Filters in asp.net MVC?

ASP.NEt MVC provides a very clean way of injecting the pre-processing and post-processing logic for actions and controllers. We can put the pre-processing and post-processing logic is by decorating the actions with attributes which will invoke an attribute class implementing  the filter's logic.

For example, If we need some action to be executed when the user has authenticated after that we can adorn the action with the [Authorize] attribute. This implements the authorization filter to check whether the user has is 
authorized or not.

[Authorize]
public ActionResult Index()
{
    return View();

}

Actually action Filters are additional attributes that can be applied to either a controller or the entire controller to modify the way in which action is executed. These attributes are special .NET classes derived from System.Attribute which can be attached to  classes, methods, properties and fields.

MVC provides the following action filters:
Output Cache: This action filter caches the output of a controller action for a specified amount of time.
Handle Error: This action filter handles errors raised when a controller action executes.
Authorize: This action filter enables you to restrict access to a particular user or role.

Types of filters

 
ASP.NET MVC supports following types of filters:
  1. Action Filters
  2. Authorization Filters
  3. Result Filters
  4. Exception Filters
Action filter
Action filter will be called before and after the action starts executing and after the action has executed. We can put our custom pre-processing and post-processing logic in this filter.

Now to implement this filter we need to create a custom filter attribute class and implement the

IActionFilter interface
This interface provides us two methods OnActionExecuting and OnActionExecuted which will be called before and after the action gets executed respectively.

public class CustomActionAttribute : FilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.Controller.ViewBag.OnActionExecuted = "IActionFilter.OnActionExecuted filter called";
    }

    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Controller.ViewBag.OnActionExecuting = "IActionFilter.OnActionExecuting filter called";
    }
}

Authorization filter
This filter provides authentication and authorization logic. It will be executed before the action gets executed. To implement this action the interface IAuthorizationFilter should be implemented by the custom attribute class.

public class CustomAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
{
    void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
    {
        filterContext.Controller.ViewBag.OnAuthorization = "IAuthorizationFilter.OnAuthorization filter called";
    }
}


Result filter
Result filter will execute before and after the result of the action method has been executed. We can use this filter if we want some modification to be done in the action's result.

IResultFilter interface
This interface provides two methods OnResultExecuting and OnResultExecuted which will be called before and after the action result respectively.

public class CustomResultAttribute : FilterAttribute, IResultFilter
{
    void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.Controller.ViewBag.OnResultExecuted = "IResultFilter.OnResultExecuted filter called";
    }

    void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.Controller.ViewBag.OnResultExecuting = "IResultFilter.OnResultExecuting filter called";
    }
}

Exception filter
Exception filter will be invoked whenever a controller or action of the controller throws an exception. This is particularly useful when we need custom error logging module.

To implement this filter we need to create a custom filter attribute class which implements IExceptionFilter. This interface gives us a methods called OnException which is a perfect place to call the exception logging module and to redirect to some error page.

public class CustomExceptionAttribute : FilterAttribute, IExceptionFilter
{       
    void IExceptionFilter.OnException(ExceptionContext filterContext)
    {
        filterContext.Controller.ViewBag.OnException = "IExceptionFilter.OnException filter called";
    }
}

Order of Execution of action filter as following

IAuthorizationFilter.OnAuthorization
IActionFilter.OnActionExecuted
IActionFilter.OnActionExecuting
IResultFilter.OnResultExecuted
IResultFilter.OnResultExecuting
IExceptionFilter.OnException


Monday, September 17, 2018

Cascading drop-down list in asp.net Grid view | Dependent Dropdownlist inside GridView


Here i am going to explain how to do cascading drop down list in asp.net webform.code is copied from my project so not able to formatted properly due to lack of time.but you see the code and understand the implementation.

.aspx code
OnRowCommand="gvCity_RowCommand" OnRowEditing="gvCity_RowEditing" OnRowCancelingEdit="gvCity_RowCancelingEdit"
 OnRowUpdating="gvCity_RowUpdating" OnRowDeleting="gvCity_RowDeleting" ShowFooter="True"
 PageSize="20" Width="100%">
 runat="server">
 AutoPostBack="true" OnSelectedIndexChanged="ddlNewCountrygvCity_SelectedIndexChanged"
 Visible="false" runat="server">
 runat="server">
 Visible="false" Enabled="false" runat="server">
 Visible="false">
 OnClientClick="return CityUpdateValidate();" ImageUrl="~/Image/update.png" ToolTip="Update"
 ToolTip="Cancel" ImageUrl="~/Image/cancel.png" />
 CommandName="AddNew" ToolTip="Add New" />
 OnClick="ibtnNewCityInsert_Click" ImageUrl="~/Image/add.png" Visible="false"
 ToolTip="Insert" /> 
 ToolTip="Cancel" ImageUrl="~/Image/cancel.png" Visible="false" />
 ImageUrl="~/Image/img_edit.png" ToolTip="Edit" />
 ImageUrl="~/Image/img_delete.png" OnClientClick="return ConfirmDelete();" ToolTip="Delete"

 .cs code
 public void gvCityBind()
 {
 dsCity = SqlHelper.ExecuteDataset(connectionString, "genCityMaster_SelectDelete", 0, "NULL", "S");
 if (dsCity.Tables[0].Rows.Count > 0)
 {
 gvCity.DataSource = dsCity;
 gvCity.DataBind();
 }
 else
 {
 NoDataFound(dsCity, gvCity);
 SrNoCity = 1;
 }
 }
 protected void gvCity_PageIndexChanging(object sender, GridViewPageEventArgs e)
 {
 gvCity.PageIndex = e.NewPageIndex;
 gvCityBind();
 }
 protected void gvCity_RowDataBound(object sender, GridViewRowEventArgs e)
 {
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
 Label lblSrNo = (Label)e.Row.FindControl("lblSrNo");
 lblSrNo.Text = Convert.ToString(gvCity.PageIndex * gvCity.PageSize + SrNoCity);
 SrNoCity++;
 DropDownList ddlCountry = (DropDownList)e.Row.FindControl("ddlCountry");
 DropDownList ddlState = (DropDownList)e.Row.FindControl("ddlState");
 if (ddlCountry != null)
 {
 ddlCountry.DataSource = objCountryBLL.SelectCounrty();
 ddlCountry.DataBind();
 ddlCountry.SelectedValue = dsCity.Tables[0].Rows[e.Row.RowIndex]["CountryId"].ToString();
 }
 if (ddlState != null)
 {
 ddlState.DataSource = objStateBLL.SelectState(Convert.ToInt32(ddlCountry.SelectedValue));
 ddlState.DataBind();
 ddlState.SelectedValue = dsCity.Tables[0].Rows[e.Row.RowIndex]["StateId"].ToString();
 }
 }
 if (e.Row.RowType == DataControlRowType.Footer)
 {
 DropDownList ddlNewCountry = (DropDownList)e.Row.FindControl("ddlNewCountry");
 DropDownList ddlNewState = (DropDownList)e.Row.FindControl("ddlNewState");
 if (ddlNewCountry != null)
 {
 ddlNewCountry.DataSource = objCountryBLL.SelectCounrty();
 ddlNewCountry.DataBind();
 }
 if (ddlNewState != null)
 {
 ddlNewState.DataSource = objStateBLL.SelectState(Convert.ToInt32(ddlNewCountry.SelectedValue));
 ddlNewState.DataBind();
 }
 }
 }
 protected void gvCity_RowCommand(object sender, GridViewCommandEventArgs e)
 {
 try
 {
 if (e.CommandName.Equals("AddNew"))
 {
 gvCity.EditIndex = -1;
 gvCityBind();
 gvCity.FooterRow.CssClass = objCommonDAL.GetGrigViewFooterStyle();
 Label lblNewSrNo = (Label)gvCity.FooterRow.FindControl("lblNewSrNo");
 lblNewSrNo.Text = SrNoCity.ToString();
 ImageButton ibtnNewCityInsert = (ImageButton)gvCity.FooterRow.FindControl("ibtnNewCityInsert");
 ImageButton imgbtnNewCancel = (ImageButton)gvCity.FooterRow.FindControl("imgbtnNewCancel");
 ImageButton imgbtnNewAdd = (ImageButton)gvCity.FooterRow.FindControl("imgbtnNewAdd");
 ibtnNewCityInsert.Visible = true;
 imgbtnNewCancel.Visible = true;
 imgbtnNewAdd.Visible = false;
 DropDownList ddlNewCountry = (DropDownList)gvCity.FooterRow.FindControl("ddlNewCountry");
 ddlNewCountry.Visible = true;
 ddlNewCountry.Focus();
 DropDownList ddlNewState = (DropDownList)gvCity.FooterRow.FindControl("ddlNewState");
 ddlNewState.Visible = true;
 TextBox txtNewCity = (TextBox)gvCity.FooterRow.FindControl("txtNewCity");
 txtNewCity.Visible = true;
 }
 }
 catch (Exception ex)
 {
 throw ex;
 }
 }
 protected void ibtnNewCityInsert_Click(object sender, ImageClickEventArgs e)
 {
 try
 {
 objCity.StateId = Convert.ToInt32(((DropDownList)gvCity.FooterRow.FindControl("ddlNewState")).SelectedValue);
 objCity.CityName = Convert.ToString(((TextBox)gvCity.FooterRow.FindControl("txtNewCity")).Text);
 objCity.CreatedBy = Convert.ToInt32(UserId);
 objCity.ModifiedBy = Convert.ToInt32(UserId);
 objCity.CreatedOn = System.DateTime.Now;
 objCity.ModifiedOn = System.DateTime.Now;
 try
 {
 int intResultInsert = objCityBLL.InsertCity(objCity);
 if (intResultInsert > 0)
 {
 exceptionMessage.Text = "Record Added Successfully !";
 gvCity.EditIndex = -1;
 gvCityBind();
 }
 else
 {
 exceptionMessage.Text = "This record already exists !";
 }
 }
 catch (Exception ex)
 {
 exceptionMessage.Text = ex.Message.ToString();
 }
 finally
 {
 objCityBLL = null;
 }
 }
 catch (Exception ex)
 {
 throw ex;
 }
 }
 protected void gvCity_RowEditing(object sender, GridViewEditEventArgs e)
 {
 gvCity.EditIndex = e.NewEditIndex;
 gvCityBind();
 }
 protected void gvCity_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
 {
 gvCity.EditIndex = -1;
 gvCityBind();
 }
 protected void gvCity_RowUpdating(object sender, GridViewUpdateEventArgs e)
 {
 try
 {
 objCity.CityId = Convert.ToInt32(((Label)gvCity.Rows[e.RowIndex].FindControl("lblCityId")).Text);
 objCity.StateId = Convert.ToInt32(((DropDownList)gvCity.Rows[e.RowIndex].FindControl("ddlState")).SelectedValue);
 objCity.CityName = Convert.ToString(((TextBox)gvCity.Rows[e.RowIndex].FindControl("txtCity")).Text);
 objCity.CreatedBy = Convert.ToInt32(UserId);
 objCity.ModifiedBy = Convert.ToInt32(UserId);
 objCity.CreatedOn = System.DateTime.Now;
 objCity.ModifiedOn = System.DateTime.Now;
 int intResultUpdate = objCityBLL.UpdateCity(objCity);
 if (intResultUpdate > 0)
 {
 exceptionMessage.Text = "Record Updated Successfully !";
 gvCity.EditIndex = -1;
 gvCityBind();
 }
 }
 catch (Exception ex)
 {
 exceptionMessage.Text = ex.Message.ToString();
 }
 finally
 {
 objCityBLL = null;
 }
 }
 protected void gvCity_RowDeleting(object sender, GridViewDeleteEventArgs e)
 {
 try
 {
 objCity.CityId = (int)gvCity.DataKeys[e.RowIndex].Value;
 int result = objCityBLL.DeleteCity(objCity);
 if (result > 0)
 {
 exceptionMessage.Text = "Row Deleted Successfully...!";
 gvCity.EditIndex = -1;
 gvCityBind();
 }
 }
 catch (Exception ex)
 {
 exceptionMessage.Text = ex.Message.ToString();
 }
 }
 protected void ddlNewCountrygvCity_SelectedIndexChanged(object sender, EventArgs e)
 {
 DropDownList ddlNewCountry = (DropDownList)gvCity.FooterRow.FindControl("ddlNewCountry");
 DropDownList ddlNewState = (DropDownList)gvCity.FooterRow.FindControl("ddlNewState");
 if (Convert.ToInt32(ddlNewCountry.SelectedValue) > 0)
 {
 ddlNewState.Enabled = true;
 ddlNewState.DataSource = objStateBLL.SelectState(Convert.ToInt32(ddlNewCountry.SelectedValue));
 ddlNewState.DataBind();
 }
 else
 {
 ddlNewState.Enabled = false;
 }
 } 

Sunday, September 16, 2018

Different return types of asp.net mvc controller action method

Q.What are different return types of a controller action method?
Answer: There are total nine return types we can use to return results from controller to view. The base type of all these result types is ActionResult.
  1. ViewResult (View): View Result is used to return a webpage from an action method.
  2. PartialviewResult (Partialview): PartialViewResult is used to send a part of a view which will be rendered in another view.
  3. RedirectResult (Redirect)RedirectResult is used to redirect to any other controller and action method depending on the URL.
  4. RedirectToRouteResult (RedirectToAction, RedirectToRoute): This return type is used when we want to redirect to any other action method.
  5. ContentResult (Content)RedirectToRouteResult is used to return HTTP content type like text/plain as the result of the action.
  6. jsonResult (json): jsonResult is used when we want to return a JSON message.
  7. javascriptResult (javascript): javascriptResult is used to return JavaScript code that will run in browser.
  8. FileResult (File): FileResult is used to send binary output in response.
  9. EmptyResult: EmptyResult is used to return nothing (void) in the result.

Page lifecycle of an ASP.NET MVC | ASP.NET page life cycle

Q.Explain “Page Life Cycle” of an ASP.NET MVC?
Ans.In traditional ASP.NET webform application each asp.net page implements the IHTTPHandler interface.
This interface has a ProcessRequest() method that gets called when you request the page. The ProcessRequest() method is responsible for processing the request and generating the response. So in asp.net application it is simple, you request for a page in the url like http://mylocalsite1\default.aspx and then it search for that page on the local disk and execute the processrequest method and generate the html response.
However in MVC application ,request response process is different from webform. In MVC there are no physical page exist for a particular request. All the requests are routed to a special class called Controller. The controller is responsible for generating the response and sending the content back to the browser.
When you build a MVC application you can define a bunch of controllers. Each controller can handle multiple requests. For example, all the following will route to same Controller.
These requests will execute the same Controller Controller1 and in that it will extract the id from the URL and process the request. This gives more readable URL then asp.net page.
So how these requests are routed to particular controller. Now the RouteTable come into the picture. Every ASP.NET MVC application has a RouteTable. This routetable is responsible to map the mvc requests to particular controller.
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollction routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
    }

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
}
When Application Start the Application_Start events will get called and it will call the method RegisterRoutes which will send the collection of Routes as the parameter and the routes will be added to this Collection which is a Dictionary of NamedMaps.
Each route also references a handler which will handle the rest of the request. When we use MapRoute, what we really do is creating a route by instantiating the 3 dictionaries and defining the default MVC handler: PageRouteHandler. Each RouteHandler implements an interface IRouteHandler.
public Route MapPageRoute(string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess, RouteValueDictionarydefaults,   RouteValueDictionary constraints, RouteValueDictionary dataTokens)
{
if (routeUrl == null)
{
throw new ArgumentNullException("routeUrl");
}
Route item = new Route(routeUrl, defaults, constraints, dataTokens, new PageRouteHandler(physicalFile, checkPhysicalUrlAccess));
this.Add(routeName, item);
return item;
}

Step 2: The URL Routing Module intercepts the request.
Whenever you make a request against an ASP.NET MVC application, the request is intercepted by the UrlRoutingModule HTTP Module. 
When the UrlRoutingModule intercepts a request, the first thing the module does is to wrap up the current HttpContext in an HttpContextWrapper object.
The HttpContextWrapper object derives from HTTPContextBase class.

private void OnApplicationPostResolveRequestCache(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication) sender;
HttpContextBase context = new HttpContextWrapper(application.Context);
this.PostResolveRequestCache(context);
}
Then the module send this contextBase object to the method called PostResolveRequestCache .
Based on the Context it will return the correct RouteData from the RouteTable which was created in the earlier step based on the URL, form parameters and query string parameters associated with the HTTPContext object. 
If the UrlRoutingModule successfully retrieves a RouteData object then the module next creates a RouteContext object that represents the current HttpContext and RouteData.
The module then instantiates a new HttpHandler based on the RouteTable and passes the RouteContext to the new handler’s constructor. 
In the case of an ASP.NET MVC application,the handler returned from the RouteTable will always be an MvcHandler. This MVCHandler also derive from interface IHTTPHandler and implement the method ProcessRequest().
The last step is it will call the RemapHandler method which will set the MVCHandler just obtained to be the Current HTTP Handler.

public virtual void PostResolveRequestCache(HttpContextBase context)
{
RouteData routeData = this.RouteCollection.GetRouteData(context);
if (routeData != null)
{
IRouteHandler routeHandler = routeData.RouteHandler;
if (routeHandler == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.GetString("UrlRoutingModule_NoRouteHandler"), new object[0]));
}

if (!(routeHandler is StopRoutingHandler))
{
RequestContext requestContext = new RequestContext(context, routeData);
context.Request.RequestContext = requestContext;
IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);
if (httpHandler == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture,  SR.GetString("UrlRoutingModule_NoHttpHandler"), new object[] { routeHandler.GetType() }));
}
if (httpHandler is UrlAuthFailureHandler)
{
if (!FormsAuthenticationModule.FormsAuthRequired)
{
throw new HttpException(0x191, SR.GetString("Assess_Denied_Description3"));
}
UrlAuthorizationModule.ReportUrlAuthorizationFailure(HttpContext.Current, this);
}
else
{
context.RemapHandler(httpHandler);
}
}
}
}

Step 4: MVC Handler Executes
MVCHandler also inherit from the IHTTPAsyncHandler. When MVC Handler executes it will call the BeginProcessRequest method of the httpAsyncHandler asynchronously.
When the process request method is called a new controller gets created. The controller is created from a ControllerFactory. There is a ControllerBuilder Class which will set the ControllerFactory. 
You can create your own ControllerFactory as well but by default it will be DefaultControllerFactory. The RequestContext and the name of the Contoller will be passed to the method CreateController Method to get the particular Contoller.
public virtual IController CreateController(RequestContext requestContext, string controllerName)
{
if (requestContext == null)
{
throw new ArgumentNullException("requestContext");
}
if (string.IsNullOrEmpty(controllerName))
{
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "controllerName");
}
Type controllerType = this.GetControllerType(requestContext, controllerName);
return this.GetControllerInstance(requestContext, controllerType);
}
Next, a ControllerContext object is constructed from the RequestContext and the controller by using the method GetContollerInstance.
Finally, the Execute() method is called on the controller class. The ControllerContext is passed to the Execute() method when the Execute() method is called.

Step 4: The Controller Executes
The Execute() method starts by creating the TempData object. TempData is a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. 
The Execute() method gets the Action from the RouteData based on the URL.The Controller Class then call the ContollerActionInvoker that builds a list of parameters from the request.
These parameters, extracted from the request parameters, will act as method parameters.The parameters will be passed to whatever controller method gets executed.
Finally It will call the InvokeAction method to execute the Action.
protected override void ExecuteCore()
{
this.PossiblyLoadTempData();
try
{
string requiredString = this.RouteData.GetRequiredString("action");
if (!this.ActionInvoker.InvokeAction(base.ControllerContext, requiredString))
{
this.HandleUnknownAction(requiredString);
}
}
finally
{
this.PossiblySaveTempData();
}
}
public virtual bool InvokeAction(ControllerContext controllerContext, string actionName)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (string.IsNullOrEmpty(actionName))
{
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "actionName");
}

ControllerDescriptor controllerDescriptor = this.GetControllerDescriptor(controllerContext);
ActionDescriptor actionDescriptor = this.FindAction(controllerContext, controllerDescriptor, actionName);
if (actionDescriptor == null)
{
return false;
}
FilterInfo filters = this.GetFilters(controllerContext, actionDescriptor);
try
{
AuthorizationContext context = this.InvokeAuthorizationFilters(controllerContext,  filters.AuthorizationFilters, actionDescriptor);
if (context.Result != null)
{
this.InvokeActionResult(controllerContext, context.Result);
}
else
{
if (controllerContext.Controller.ValidateRequest)
{
ValidateRequest(controllerContext);
}
IDictionary<string, object> parameterValues = this.GetParameterValues(controllerContext,actionDescriptor);
ActionExecutedContext context2 = this.InvokeActionMethodWithFilters(controllerContext,filters.ActionFilters, actionDescriptor, parameterValues);
this.InvokeActionResultWithFilters(controllerContext, filters.ResultFilters, context2.Result);
}
}
catch (ThreadAbortException)
{
throw;
}
catch (Exception exception)
{
ExceptionContext context3 = this.InvokeExceptionFilters(controllerContext,filters.ExceptionFilters, exception);
if (!context3.ExceptionHandled)
{
throw;
}
    this.InvokeActionResult(controllerContext, context3.Result);
}
return true;
}

Step 5: The Render View Method is called
The Controller typically either executes either the RedirectToAction Method or the RenderView Method. When you call a controller’s RenderView() method,the call is delegated to the current ViewEngine’s RenderView() method.
 The WebFormViewEngine.RenderView() method uses a class named the ViewLocator class to find the view. Next, it uses a BuildManager to create an instance of a ViewPage class from its path.
Next, if the page has a master page, the location of the master page is set If the page has ViewData, the ViewData is set. Finally, the RenderView() method is called on the ViewPage.


The ViewPage class derives from the base System.Web.UI.Page class. This is the same class that is used for pages in classic ASP.NET.
The final action that RenderView() method performs is to call ProcessRequest() on the page class. Calling ProcessRequest() generates content from the view in the same way thatcontent is generated from a normal ASP.NET page.

What are the advantages of ASP.NET MVC

Q.What are the advantages of ASP.NET MVC 
Answer: 
Multi view support
Due to the separation of the model from the view, the user interface can display multiple views of the same data at the same time.

Separation of Concerns
Separation of Concerns is one of the core advantages of ASP.NET MVC .Since code-behind concept has been removed from MVC
The MVC framework provides a clean separate logic for the UI, Business Logic, Model or Data.This feature enable code re-usability.

More Control
The ASP.NET MVC framework provides more control over HTML, JavaScript and CSS than the traditional Web Forms.

Testability Is Easy
ASP.NET MVC framework provides better testability of the Application and good support for the test driven development too.

Lightweight
ASP.NET MVC framework doesn’t use View State and thus reduces the bandwidth of the page.

Thursday, August 23, 2018

JQuery Interview Questions and answers

1.What are the basic selectors in jQuery?

Following are the basic selectors in jQuery:

A)Element ID
    A ID available the DOM Using ID we can axxess the control in JQuery.

using JQuery
$("#EmpId")

B)CSS Name
     A  class name will be available in the DOM usinf class name we can access this in JQuery.

using JQuery
$(".Menu")

C)Tag Name
    A tag name available in the DOM. For example $('a') selects anchor tags in the DOM.

using JQuery
$("a")

Monday, August 20, 2018

Free source code Version Control Systems

SVN
Subversion is the most used version control used in worldwide. Most open-source projects use Subversion as a repository because other larger projects, such as SourceForge, Apache, Python, Ruby and many others, use it as well.Because of its popularity, there are many versions and IDEs available.

Git
Git is the new fast-rising version control systems. Initially developed by Linux kernel creator Linus Torvalds, Git has recently  taken the Web development community by storm. Now Git has quickly emerged as a preferred version control system in nowadays.
 Thanks to its distributed form of control without any master copy of the software, many open
 source projects and system administrators prefer Git. Let us have a look at the key pros and cons of this system.

Sunday, August 19, 2018

Required Field Validator not Working For DropDownList asp.net

You need to set the value as 0 in the InitialValue of validator or change the value of first item of DropDown.



cssclass="required" display="dynamic" errormessage="*" setfocusonerror="true"

InitialValue="0">

Wednesday, August 15, 2018

State Management techniques In ASP.NET MVC


State Management In ASP.NET MVC.
 We all know that HTTP is a state less protocol. Hence, If we want to pass data from one page to another page or even on multiple  
 visits of the same page, then we need to use the State management techniques to store user specific data.  
 Here, i am going discuss various techniques to pass the data from a Controller to View or Controller to Controller.  
 ASP.NET MVC doesn’t support ViewState or Server controllers.  
 To achieve state management in ASP.NET MVC, there are four basic ways which are given as following.  
 1.ViewData  
 2.ViewBag  
 3.TempData  
 4.Sessions  
 1.ViewData  
 ViewData is used to pass the data from Controller to View.It is derived from ViewDataDictionary class, it requires typecasting for complex datatypes   
 and it requires a null check to void exceptions.  
 Controller  
 public ActionResult Index()   
     {   
       ViewData["CurrTime"] = DateTime.Now;   
       return View();   
     }   
 HTML Index.cshtml Code  
 @ViewData["CurrentTime"];  
 2.ViewBag  
 ViewBag is also used to pass data from Controller to View. It is a dynamic property which uses the Dynamic feature of C# 4.0. And, the  
 Dynamic keyword internally uses reflection.  
 Controller Code  
 public ActionResult Index()   
     {   
       ViewBag.CurrTime = DateTime.Now;   
       return View();   
     }   
 html Index.cshtml code  
 @ViewBag.CurrentTime  
 3.TempData  
 TempData is used to pass the data from Action to Action or Controller to Controller, and then to View. It keeps the information for single HTTP Request.  
 It is derived from TemDataDictionary and along with this, it requires typecasting for complex data types and it requires a null check to void exceptions.  
 Controller Code  
 public ActionResult Index()   
     {   
       TempData["CurrTime"] = DateTime.Now;   
       return View();   
     }   
 Html Index.cshtml code  
 @TempData["CurrTime"];  
 4.Session  
 If you want to store the data and maintain it for multiple requests, then use session variables.  
 Controller Code  
 public ActionResult Index()   
     {   
 Session["CurrTime"] = DateTime.Now;   
       return View();   
     }   
 Html Index.cshtml Code  
 @Session["CurrentTime"];  

How to Upload Files in ASP.NET MVC

 Upload Files In ASP.NET MVC
Here i am going to explain File Upload example in ASP.Net MVC  
 Below code is quite limited and simple functionality for single file upload, and it will work in any browser.  
 Before uploading the file, we will check whether Directory exists if not exist then the Directory will be created.  
 View  
 View consists of an HTML form containing the submite button, which open a select file dialog, and Submit, which sends the chosen file to  
 the server in a POST request.  
 <html>  
 <head>  
   <meta name="viewport" content="width=device-width"/>  
   <title>Index</title>  
 </head>  
 <body>  
   <div>  
     @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
     {  
       <span>Select File:</span>  
       <input type="file" name="postedFile"/>  
       <hr/>  
       <input type="submit" value="Upload"/>  
       <br/>  
       <span style="color:green">@ViewBag.Message</span>  
     }  
   </div>  
 </body>  
 </html>  
 Controller  
 public class HomeController : Controller  
 {  
   // GET: Home  
   [HttpGet]  
   public ActionResult Index()  
   {  
     return View();  
   }   
   [HttpPost]  
   public ActionResult Index(HttpPostedFileBase postedFile)  
   {  
     if (postedFile != null)  
     {  
       string path = Server.MapPath("~/Upload/");  
       if (!Directory.Exists(path))  
       {  
         Directory.CreateDirectory(path);  
       }   
       postedFile.SaveAs(path + Path.GetFileName(postedFile.FileName));  
       ViewBag.Message = "File uploaded successfully.";  
     }   
     return View();  
   }  
 }  

JQ GRID in ASP.NET MVC 4 using Razor

 JQ GRID Using MVC with Razor View Engine in ASP.NET MVC 4  
 Friends,Here i am going to explain how to use jqgrid in asp.net mvc4 with rzor view engine.JQGrid is one of the most flexible and stable
 gird you can find in the current tech market. It’s free to use. Here i am going to write basic step to do where data will come from 
database to show in JQgrid.  
 Following are step by step sequence to create the JQGRID.  
 1.Create a new ASP.NET MVC 4 Web Project  
 2.Select Empty template with Razor   
 4.Right Click on the Controller and Add new Controller  
 5.Copy and paste the below code in the controller as fllowing  
 using System;  
 using System.Collections.Generic;  
 using System.Web;  
 using System.Web.Mvc;  
 using System.Data;  
 using System.Data.SqlClient;  
 using System.Configuration;  
 using JQGridExample.Models;  
 namespace JQGridExample.Controllers  
 {  
   public class EMPLOYEEController : Controller  
   {  
     public ActionResult EmpDetails()  
     {  
       return View();  
     }  
     public JsonResult getEmpDetails()  
     {  
       List<Employee> items = new List<Employee>();  
       items = getData();  
       var a = Json(items, JsonRequestBehavior.AllowGet);  
       a.MaxJsonLength = int.MaxValue;  
       return a;  
     }  
     public List<Employee> getEmpData()  
     {  
       string connString = ConfigurationManager.ConnectionStrings["Mycon"].ConnectionString;  
       SqlConnection conn = new SqlConnection(connString);  
       SqlCommand cmd = new SqlCommand();  
       cmd.CommandTimeout = 6000;  
       cmd.CommandText = "select * from employee";  
       cmd.Connection = conn;  
       conn.Open();  
       DataTable dataTable = new DataTable();  
       SqlDataAdapter da = new SqlDataAdapter(cmd);  
       da.Fill(dataTable);  
       conn.Close();  
       da.Dispose();  
       List<Employee> items = new List<Employee>();  
       foreach (DataRow row in dataTable.Rows)  
       {  
         items.Add(new MEmployee  
         {  
           Id = row["ID"].ToString(),  
           Name = row["Name"].ToString(),  
           Gender = row["Gender"].ToString(),  
           Contact = row["Contact"].ToString(),  
           Address = row["Address"].ToString(),  
           State = row["State"].ToString(),  
                          Country = row["Country"].ToString()  
         });  
       }  
       return items;  
     }  
   }  
 }  
 6.Add new class to the Model folder and paste the below code in the Model.  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 namespace JQGridExample.Models  
 {  
   public class Employee  
   {  
     public string Id { get; set; }  
     public string NAME { get; set; }  
     public string Name { get; set; }  
     public string Gender { get; set; }  
     public string Contact { get; set; }  
     public string Address { get; set; }  
           public string State { get; set; }  
           public string Country { get; set; }  
   }  
 }  
 8. Right Click on the Controller and Add the View ,name should be EmpDetails  
 9. Add below code to the created EmpDetails view  
 @{  
   ViewBag.Title = "JQGrid Esample";  
 }  
 <html>  
 <head>  
   <title>My First JQGrid Example</title>  
 <script src="~/Scripts/jquery-1.11.0.min.js"></script>  
 <link href="yourlocalpath/ajax/libs/jqueryui/1.8.13/themes/base/jquery-ui.css" rel="stylesheet" />  
 <script src="yourlocalpath/jqgrid/4.6.0/jquery.jqGrid.min.js"></script>  
 <script src="yourlocalpath/jqgrid/4.6.0/i18n/grid.locale-en.js"></script>  
 <script src="yourlocalpath/jqgrid/4.6.0/jquery.jqGrid.min.js"></script>  
 <link href="yourlocalpath/jqgrid/4.6.0/css/ui.jqgrid.css" rel="stylesheet" />  
   <style type="text/css">  
     .ui-jqgrid .ui-widget-header {  
       background-color: #336699;  
       background-image: none;  
       color: white;  
     }  
     .ui-jqgrid .ui-jqgrid-labels th.ui-th-column {  
       background-color: #FFCC66;  
       background-image: none;  
       color: #336699;  
       height: 30px;  
       font-weight: bold;  
     }  
   </style>  
   <script type="text/javascript">  
     $(function () {  
       $("#myEmpGrid").jqGrid({  
         url: '@Url.Action("getEmpDetails")',  
         datatype: 'json',  
         mytype: 'get',  
         colNames: ['Id','Name', 'Gender', 'Contact', 'Address', 'State','Country'],  
         colModel: [  
 { name:'Id', width:'35px' },  
 { name:'Name', width:'160px' },  
 { name:'GENDER' },  
 { name:'Gender' },  
 { name:'Address' },  
 { name:'State'},  
 { name:'Country'}  
               ],  
         pager: $('#myPager'),  
         rowNum: 5,  
         sortname: 'ID',  
         gridview: true,  
         sortorder: 'desc',  
         loadonce: true,  
         rowList: [5, 10, 20, 50],  
         width: 600,  
         height: 110,  
         viewrecords: true,  
         caption: 'Emp details in JQ Grid'  
       });  
     });  
   </script>  
 </head>  
 <body>  
   <div>  
     <table id="myEmpGrid"></table>  
     <div id="myPager"></div>  
   </div>  
 </body>  
 </html>  
 Run your application and test   

Tuesday, August 22, 2017

JQuery date picker in asp.net

Here am going to explained with an example , how to implement jQuery UI DatePicker Calendar with ASP.Net TextBox.
.aspx code
 <script src="../Scripts/jquery-1.12.4.min.js" type="text/javascript"></script>   
 <script src="../Scripts/jquery-ui-1.12.1.min.js" type="text/javascript"></script>  
 <link href="../Content/themes/base/jquery-ui.css" rel="stylesheet" rel="Stylesheet" type="text/css" />  
 <script type="text/javascript">  
   $(function () {  
     $("[id*=txtDate]").datepicker({  
       showOn: 'button',  
       buttonImageOnly: true,  
       buttonImage: 'images/calendar.png'  
     });  
   });  
 </script>  
  <div class="form-inline" role="form">  
    <div class="form-group">  
           <asp:TextBox ID="txtDate" runat="server" ReadOnly = "true"></asp:TextBox>  
           <asp:Button ID="btnSubmit" runat="server" Text="Submit"  
     onclick="btnSubmit_Click" />  
      </div>  
 </div  

Thursday, August 10, 2017

ASP.NET MVC interview questions & answers

What is MVC (Model View Controller)?
Answer: 
MVC is an architectural pattern which separates the UI and Data Model and business logic. It’s divided into three parts, Model, View, and Controller.

1. The Model represents the data and pass it to view (Database objects).
2. The View displays the data and responsible for look and feel of the page (from database).
3. The Controller handles the user input(request) and load appropriate model and view.

What are the advantages of MVC?
Answer: 
Multi view support
Due to the separation of the model from the view, the user interface can display multiple views of the same data at the same time.

Separation of Concerns
Separation of Concerns is one of the core advantages of ASP.NET MVC .Since code-behind concept has been removed from MVC
The MVC framework provides a clean separate logic for the UI, Business Logic, Model or Data.This feature enable code re-usability.
Read More...

Q.Explain “page lifecycle” of an ASP.NET MVC?
When a page is requested first following process are performed by ASP.Net MVC 
Step 1: Routing
In traditional ASP.NET webform application each asp.net page implements the IHTTPHandler interface.
This interface has a ProcessRequest() method that gets called when you request the page. The ProcessRequest() method is responsible for processing the request and generating the response. So in asp.net application it is simple, you request for a page in the url like http://mylocalsite1\default.aspx and then it search for that page on the local disk and execute the processrequest method and generate the html response.
However in MVC application ,request response process is different from webform. In MVC there are no physical page exist for a particular request. All the requests are routed to a special class called Controller. The controller is responsible for generating the response and sending the content back to the browser.
When you build a MVC application you can define a bunch of controllers. Each controller can handle multiple requests. For example, all the following will route to same Controller.
http://mylocalsite1/Controller1/2
http://mylocalsite1/Controller1/3


Question 4: What are different return types of a controller action method?Answer: There are total nine return types we can use to return results from controller to view. The base type of all these result types is ActionResult.
  1. ViewResult (View): View Result is used to return a webpage from an action method.
  2. PartialviewResult (Partialview): PartialViewResult is used to send a part of a view which will be rendered in another view.
  3. RedirectResult (Redirect)RedirectResult is used to redirect to any other controller and action method depending on the URL.
  4. RedirectToRouteResult (RedirectToAction, RedirectToRoute): This return type is used when we want to redirect to any other action method.
Read More...

Question 5 : What are action filters in aspnet mvc?
Answer : ASP.NET MVC provides a very clean way of injecting the pre-processing and post-processing logic for actions and controllers. We can put the pre-processing and post-processing logic is by decorating the actions with attributes which will invoke an attribute class implementing  the filter's logic.
Read More...