Tuesday, March 17, 2015

Bind data to dropdownlist on change parent dropdown event using jquery Ajax in MVC Razorview.

There is various way to bind dropdownlist in MVC using Razorview. but if you want to bind dropdownlist according to change event of another dropdownlist selected item change event then you can do this through jquery .ajax method and through JsonResult as given below.

Create Model in your MVC Project.

   public class ProductModel
    {
        public string Category { get; set; }
        public string Products { get; set; }

    }

Create Simple RazorView for binding Dropdownlist.

add model reference on top of this view
@model sampleApplication.Models.ProductModel

and add html helper dropdown list

@Html.DropDownListFor(m => m.Category, new SelectList(ProjectUtils.GetCategories(), "Id", "Name"), "--Categories--")
@Html.DropDownListFor(m => m.Products, new SelectList(ProjectUtils.GetProducts(), "Id", "Name"), "--Products--")

Create JQuery function for selected category dropdown to get productlist of that category.


Create Controller and add below functions for fetch data from database according to pass category id.


This is the complete process for binding dropdownlist on selection change event.I hope you like this post i would like to give your feedback or comment.

Friday, March 13, 2015

Difference between Finalize & Dispose Method in Asp.net

Here i am going to describe the difference between Finalize & Dispose Method in Asp.net
Finalize

  • Finalize method internally called by Garbage collector which is the features of .Net Framework it cannot called by user.
  • if is there any free unmanaged resources such as files, variables, database objects & connections that will destroyed.
  • It is associated with Object Class.
  • Performance will matter in case of Finalize method.

Dispose

  • Dispose Method explicitly called by user and must be implement with IDisposable interface.
  • Anytime we can use this method for any free unmanaged resources such as files, variables, database objects & connections
  • It is associated to IDisposable interface.
  • Performance will not matter in case of Dispose method.

In this article i try to explain Finalize & Dispose Method difference. i hope this information will help you to understand the difference between both of them still if you have any query then you can post your feedback or comment.

Wednesday, March 11, 2015

Difference between IEnumerable & IQueryable

I have read lots of articles of difference between IEnumerable and IQueryable over internet and finally i got proper answer which i have written here

Both are using for data manipulation. IQueryable has all the features of IEnumerable. Both have its own significant for query data & data manipulation.

IEnumerable

  • System.Collections is the Namespace for IEnumerable class.
  • When Select Query On Server side at that time load data in-memory on client side then filter . suppose if we pass filter option in query like Top 10 or Max 5 then it will work on client side.
  • It means after loading full data collections like list or array list data filter from there.

IQueryable

  • System.Linq is the Namespace for IQueryable class.
  • When Select Query On Server side data filter options will also handle in server side it means data will comes up with filtering done.
  • IQueryable is best when using remote database.

In this article i try to explain IEnumerable and IQueryable difference. i hope this information will help you to understand the difference between both of them still if you have any query then you can post your feedback or comment.

Wednesday, January 7, 2015

Required Jquery or javscript for MVC Projects.

Below is the list of jquery required to load ajax and mvc validations successfully.


  • JQuery JavaScript Library ( download latest version Click Here )
Define in Mvc Razor View :
<script src="@Url.Content("~/Assets/js/jquery-1.10.2.min.js")" type="text/javascript"></script>


  • JQuery UI ( download latest version Click Here )
Define in Mvc Razor View :
<script src="@Url.Content("~/Assets/js/jquery-1.10.3-ui.min.js")"></script>


  • Unobtrusive Ajax ( which is already in mvc project "Scripts" folder )
Define in Mvc Razor View :
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>

Note : for calling ajax request you need to replace ".live" with ".on" in this script. 


  • MVC Validation Jquery ( which is already in mvc project "Scripts" folder )
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script> 


Thursday, November 20, 2014

Invalid object name dbo.table's in Entity Framework


Entity Framework which is created Default Table Name when create Data context.

You need to remove Default Plural Table Name.

for that add one line code in auto generated mathod name "OnModelCreating"


  protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //throw new UnintentionalCodeFirstException();
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }


I hope this solution will help you to solve your problem. if you have any query then post comment or leave your feedback or you can mail me at mehulpatelk152@gmail.com.

Thursday, November 13, 2014

Action Filters & their Attributes In Asp.Net MVC4

Action Filter will help you to perform extra oprations while MVC Controller or Action before Executing or After Executed. We can check authorize user by using "IAuthorizationFilter" interface. Exception handling is also managed by "IExceptionFilter" interface. we can also call Action Filter from global file register with below code.


Go to Global.asax file


Register Filter at application level.


Go to Filter.config in App_Start folder.


Add Custom Filter here filter.config file


ActionFilterAttribute represents the base class of filter attributes.which is contains The filter context as below


this method will call after the action method method executes.

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
}


this method will call after the action result executes.

public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
}


this method will call before the action method executes.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}


this method will call before the action result executes.

public override void OnResultExecuting(ResultExecutingContext filterContext)
{
base.OnResultExecuting(filterContext);
}


Later on we can use in the Controller on which action attribute to execute.

Call Filter on top of the controller as below

[Authorize]
public class UserController : Controller
{
}

Call Filter on top of the Action as below

public class UserController : Controller
{
[Authorize]
public ActionResult Login(string username)
{
// Logic
return View();
}
}


I hope you like this post. If you have any query regarding Action filters then you can post your feedback or send me email at mehulpatelk152@gmail.com.

Explain the difference between ViewData, Viewbag, Tempdata?

We used Session, ViewState, Querystring, Hiddenfield variables in .Net for persisting value. In MVC we can maintain user session in three ways tempdata, viewbag, viewdata.

Here is the difference between them and in which case we need to use that?


TempData :

  • tempdata value maintain from One controller to other controller or from one action to another action. tempdata works internally same like session. tempdata is available for current request, it will not available for subsequest request after read or assign to variable. if we want to use for subsequest request as well then we need to use "Keep" Method which is used as below code.

    string UserName = tempdata["Name"];

    tempdata.keep("Name");

  • Controller to Controller - in this case, we need to use Tempdata.

View data:

  • viewdata value maintain when you move from Controller to View.
  • Controller to View - in this case, we need to use Viewdata.

View Bag:

  • viewbag is used dynamic object internally. type casting is not required at the time of assing value.
  • Controller to View - in this case, we need to use Viewbag.

I hope you like this post. If you have any query then post your comment here or you can contact me at mehulpatelk152@gmail.com.

Saturday, November 8, 2014

Validations in Asp.Net MVC

First we need to add namespace in top of the model class
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema;

Data Annotation validation apply on specific property of model class. here i explain different types of validation attributes example as below.
Required data annotation attribute.



"Required" attribute can have different parameters such as "ErrorMessage" for validation error message statically, "ErrorMessageResourceName" for validation error message key which is came from Global Resource file. You can use either "ErrorMessage" parameter or "ErrorMessageResourceName" and "ErrorMessageResourceType".

In Order to display validation error message in View or Partial View by using "ValidationMessageFor" Html helper.



Lastly, the controller we can check if the model is proper valid or not by using the "ModelState.IsValid" property and accordingly we can redirect to view.



For other validation Attributes I have explain in details as below.

If you want to check string length, you can use "StringLength" attribute
[StringLength(160)]
public string FirstName { get; set; }

If you want to check regular expression, you can use the "RegularExpression" attribute.
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email { get; set; }

If you want to check whether the numbers are in range, you can use the "Range" attribute.
[Range(10,25)]public int Age { get; set; }

If you want to check Custom Validation for Email whether this email is already registered or not, you can use the "CustomValidation" attribute and for that you can check by action of that controller by Remote attribute.



If you would like to compare the value of one field with another field, we can use the "Compare" attribute.
[Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "PasswordRequired")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "ConfirmPasswordRequired")]
[DataType(DataType.Password)]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "PasswordDoNotMatch")]
public string ConfirmPassword { get; set; }


If you would like to check the URL is valid or not, we can use the "Url" attribute.
[Display(Name = "Facebook")]
[Url(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "ValidFaceBookAddress", ErrorMessage = null)]
[DataType(DataType.Url)]
public string Facebook { get; set; }

If you want to check atleast one checkbox checked then you have to use "CheckList" attribute which is creating dynamically
[CheckList(1, false, ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "Atleast1PaymetnMode")]
[Display(Name = "Payment Mode")]
public List PaymentMode { get; set; }

I tried my best to explain in details about validtion in MVC still you have any query regarding this question then you can comment or contact us on mehulpatelk152@gmail.com

Friday, November 7, 2014

What is the difference between ActionResult & ViewResult?

ActionResult is Base class while ViewResult is Derived class which is inherit from base class. ActionResult has various derived class such as "ViewResult", "JSONResult", "FileStreamResult"

ActionResult which is used as Polymorphism. if want to returning multiple views dynamically under one action then "ActionResult" is the best thing.

below is the code you can see Action call dynamic views depending on return Results.
Action


I hope you understand the differece between ViewResult & ActionResult. If you have any query regarding this question then you can comment or contact us on mehulpatelk152@gmail.com

A potentially dangerous Request.Form value was detected from the client error In MVC

I got this error when i have submited Html.Begin Form in MVC Razor, for that i have used ckeditor biding with Description field in model and when i have content with enter or new line i got this error.

You have to check below options when you got this error.

[AllowHtml]
The model add this attribute for each property that you want allow HTML.

[ValidateInput(false)]
This attribute will add above controller action to allow HTML.

You should do also some settings in Web.config file 

This settings which is related in HttpRuntime and pages according to requestValidationMode="2.0" and validateRequest="false" attribute in the pages element.


I think this settings will help you to find out this problem solutions. if you have still any error or confusion regarding this question leave here your comment or email me at mehulpatelk152@gmail.com

Friday, October 17, 2014

Difference between View & Partial View in Asp.net MVC.

View & Partial View both render html in page so the difference that i identified between View and PartialView is :

View :

View can contains a complete html with multiple Partial view

View can have specific Layout ( Master Page in Aspx)

View that can be updated through normal @Html.BeginForm() & @Html.ActionLink()


Partial View :

Partial View are more lightweight then Standard View.

Partial View does not contains any Layout

Partial View Consider like a control in webforms, it is reusable.

we can use multiple partial view in single view.

Basically Partial View that can be updated through AJAX requests @Ajax.BeginForm() & @Ajax.ActionLink()


I hope this information will enought to understand about the difference between view & partial view. If you have still any error or confusion regarding this question leave here your comment or email me at mehulpatelk152@gmail.com

Thursday, October 16, 2014

What is Asp.net Mvc Framework ?


MVC stands for Model, View, Controller architecture. Asp.Net MVC is architecture to develop web application with MVC are even more SEO friendly.

for developing Asp.net MVC application require .Net Framework 3.5 or higher.


MVC FRAMEWORK






What is MODEL?

  • Model is basically entity or c# class.
  • Model is accessible by Controller & View.
  • Model pass data from Controller to View. When Submit form then call Controller action and pass model data to database and return view or partial view with Model.
  • Model is use to display data in View.


What is CONTROLLER?


  • Controller is basically a collection of action methods which are responsible for calling view or partial view.
  • Controller is base of MVC architecture
  • Controller can access and use model class to pass data to views
  • Controller can access model to pass data to views
  • Controller use ViewData, ViewBag, TempData to pass data to View


What is VIEW?


  • View is Aspx or Razor without having cs or vb file.
  • View can be call only from a controller’s action method
  • View can have Ajax.Beginform and Html.Beginform for submit data with optional parameters
  • View can have multiple partial view using  @Html.RenderPartial("partialviewname") or   @Html.Partial("partialviewname")



I hope you understand about Mvc Framework after read this post. if you have any query regarding
Mvc Framework you can comment or contact us on mehulpatelk152@gmail.com.