Skip to main content

Posts

Showing posts with the label Asp.net mvc

Asp.net mvc 3 DataAnnotation using IValidatableObject for multiple properties.

If you have a scenario in which you want to base a validation on multiple business logics on multiple properties then you should consider using IValidatableObject . One of the advantages is that you can use the properties attributes directly which open door to a lot of validation possibilities. It will only be called when there are no individual properties error. It doesn't support clientside validation. Below is the simple code that will give you insight of how this all works. public class User : IValidatableObject { [Key] public string UserId { get; set; } [Required] public string UserName { get; set; } [Required] public string Password { get; set; } [Compare("Password")] public string ConfirmPassword { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { List<ValidationResult> err = new List<ValidationResult...

Asp.net mvc entity framework code first appoach.

Entity Framework comes with three approaches for development. 1) Database First: In this approach you already have your database and the entity framework will generate the model for you. 2) Model First: You don't have the database in this approach and you manually create the domain model using the entity framework designer. After creating the model the designer will generate the ddl statement which will be used to create the database. 3) Code First which I am covering in this post was introduced in EF 4.1. Code first allows you to create the domain model in the code without using the designer. After that EF will be generating the database for you. This approach is used only if you don't have the database the first time. If the database exists use the first approach. So here how the things goes. public class User { [Key] public int UserID { get; set; } [Required] public string UserName { get; set; } [Required] public string Password { get; set;...

Asp.net mvc DataAnnotation ValidateAttribute two properties comparison.

Using Datannotion is great but there are scenarious in which the current attributes compare, range etc becomes inadequate especially for the comparisions. So we create here our own custom validation using ValidationAttribute class which is the base class for all the annotation attributes. So by deriving from it and overriding the Isvalid method we can create our custom attribute for the model. So here is the scenario in which I will be validating the Username against the password which should not be equal. Compare attribute cannot be used in this scenario so I have created a custom attribute for that. Here is the model with the attribute. User View Model [CompareUserPass("UserName", "Password", ErrorMessage = "UserName and password cannot be equal")] public class UserView { [Required(ErrorMessage = "UserName Required")] public string UserName { get; set; } [Required(...

Asp.net mvc model binding security.

One of the thing that makes asp.net.mvc so interesting is default model binding. Model binding in simple words allows you to take the posted form data from the view and bind it to the action method's parameter in the controller without any fuss. But there is a security flaw in model binding which everyone using asp.net mvc should know .The problem is, in asp.net mvc controller you cannot be sure what you got as the posted value from the view because it is absolutely possible that an extra property, or an overwritten property which you don't want get passed to the controller which could spell disaster. And in the controller if the property matches the orginal property then the things could get out of hand. Here's a simple scenario to understand more what I have defined. A person filling a create user form to become the member of the website requiring some payment in the process passed an Isenabled=true property (which we all have) and unfortunately there is a match in the mo...

Asp.net mvc using AutoMapper simplified.

Most of the time in the real world applications it is not possible to map the database model to your presentation view directly because of the fact you may need some additional fields in your view. Using view Data or Viewbag is not always the good idea as it may make things harder or less elegant which are much easier to do. We are creating the User create view as an example here in which confirm password field is additional field in the view and it has nothing to do with the database model. So in this case you would create one model for the database fields as usual and one extra model for the view. The problem is that in the controller you have to map each property from your model for the database to the model for the view manually which shouldn't be done because it is not a good practice as there is a tool for that. The third party tool the Automapper solves this problem by automatically mapping your view model which you get from the view in the controller to the database mod...

Asp.net mvc using JsonResult

Json has become one of the most popular form of data interchange method and being tightly integrated in the mvc framework makes it very easy to use. I will be demonstratating a very usefull technique of passing a response in an Ajax style using JsonResult (It is a class that is used in mvc framework to pass a json formatted content to the response). Model public class Users { public int UserId { get; set; } public string UserName { get; set; } } Controller public ActionResult Index() { return View(); } public JsonResult GetUsers() { List<Users> users = new List<Users>() { new Users { UserId =1, UserName ="kaunain" }}; return this.Json(users,JsonRequestBehavior.AllowGet); } View <script type="text/javascript" language="javascript"...

Asp.net mvc razor render partial view using ajax helper

This is the extension to my blog in which I demonstrated rendering of the partial view using jquery Ajax . I want to demonstrate here yet another way by which partial view can be rendered without page refresh. Here is the implementation. Step 1: I will again be using DisplayData class in my demo. Here is it. public class DisplayData { public int ID { get; set; } public DisplayData(int ID) { this.ID = ID; } } Step 2: Create a PartialDemo page @model IEnumerable<MvcApplication5.Models.DisplayData> @{ ViewBag.Title = "PartialDemo"; } @Ajax.ActionLink("Click 1", "PartialDemo", "PartialDemo", new {Data= "1" }, new AjaxOptions { UpdateTargetId = "rsvpmsg" }) @Ajax.ActionLink("Click 2", "PartialDemo", "PartialDemo", new {Data= "2" }, new AjaxOptions { UpdateTargetId = "rsvpmsg" }) <div id="rsvpms...

My Asp.net mvc,Asp.net, linq and jquery Faqs

Here I want to make the list of every thing about Asp.mvc, linq and jquery I have been involved in or I can get my hands on or find very interesting. The list will keep on growing over time. How to get the current Route Id in the view from Url? <%=Url.RequestContext.RouteData.Values["id"] %>  What is difference between Html.Partial and Html.RenderPartial? Good complete answer here. What is Mvc Futures Library? Please refer here for the answer. http://stackoverflow.com/questions/2734316/asp-net-mvc-futures-refresh-for-mvc2. What is TempData? Answer here What is Difference between ViewData and ViewBag? See here And here Many to Many Relationship in linq to sql ? http://geekswithblogs.net/WinAZ/archive/2010/01/09/simplified-many-to-many-relationships-with-linq-to-sql.aspx http://www.codeproject.com/KB/linq/linq-to-sql-many-to-many.aspx http://www.iaingalloway.com/many-to-many-relationships-in-linq-to-sql-part-2 How to catch error in Jquery's load ...

Asp.net mvc having multiselect with the listbox

Populate the Listbox with MultiSelect. Controller: public ActionResult Create() { var Degree=DegreeRepository.GetAllDegree(); ViewData["Degree"] = new MultiSelectList(Degree, "DegreeId", "DegreeName"); return View(); } Here I want to mention if you want the single selection for the Listbox you can use SelectList as I mentioned here View <%: Html.ListBoxFor(model => model.DegreeId, ViewData["Degree"] as MultiSelectList) %> Population and then selection of item in the dropdownList.  Controller: public ActionResult Edit(int id) { var Users=UserRepository.GetUser(id); var Degree=DegreeRepository.GetAllDegree(); ViewData["Degree"] = new SectList(Degree,"DegreeId","DegreeName",Users.DegreeId); return View(); } View: <%: Html.DropDownListFor(model => model.DegreeId, ViewData["Degree"]) %>

Asp.net mvc Dropdownlist population and selection

Populate the dropdownList. Controller public ActionResult Create() { var Degree=DegreeRepository.GetAllDegree(); ViewData["Degree"] = new SelectList(Degree, "DegreeId", "DegreeName"); return View(); } View <%: Html.DropDownListFor(model => model.DegreeId, ViewData["Degree"]%> Population and then selection of item in the dropdownList. Controller public ActionResult Edit(int id) { var User=UserRepository.GetUser(id); // Get Single User var Degree=DegreeRepository.GetAllDegree(); // Get All Degrees ViewData["Degree"] = new selectList(Degree,"DegreeId",DegreeName",User.DegreeId); return View(); } View <%: Html.DropDownListFor(model => model.DegreeId, ViewData["Degree"] %>

Asp.net mvc c# changing the dateformat

There are times when you need to change the datetime format of the default date generated by System.DateTime.Now to some other. Here how you can do it string datetFormat = "dd-MMMM-yyyy hh:mm"; string date = Convert.ToDateTime(datetime).ToString(datetFormat); It will generate 11-February-2011 06:13

How to use Asp.net mvc JavaScriptResult practically

I am usually very excited about knowing something that can make my life easy and JavaScriptResult is one of that thing. It is used to execute JavaScript code immediately on the client sent from the server. Here is the small code snippet for its implementation. View:  <%: Ajax.ActionLink("display", "Display", new AjaxOptions()) %> <%: Html.TextBox("name","mazhar") %> <%: Ajax.ActionLink("checks", "Checks", new AjaxOptions()) %> Controller: public ActionResult Display() { var script = "$('#message').append('Display');"; return JavaScript(script); } public ActionResult Checks() { string script = "var textboxvalue=$('#name').val();"; script += "$('#message').append(textboxvalue);"; return JavaScript(script); } Output: 1) Clicking on the first link will display Display in the message div. 2) Cli...