Json Post and Get in Asp.net MVC

. Thursday, October 13, 2011
0 comments



What is Json ?


Json stands for javascript object notation which is used to interchange data between various languages a typical example is any server side language like c#,vb.net with Javascript.


How to use Json in MVC ?

well,whenever you make an Ajax Call to retrieve some sort of data then the best format to retrieve data is Json which is string:value pair.
get more about json here

Now lets create a Html to Make an Ajax call and retrieve Json.

What time is it?

<% using (Ajax.BeginForm("GetTime", new AjaxOptions { UpdateTargetId = "myResults" })) { %> Show me the time in: <% } %>
Results will appear here
This page was generated at <%= DateTime.UtcNow.ToString("h:MM:ss tt") %> (UTC)
Confirmation Dialog..

which looks like as follows :






















Now my Javascript with making ajax call is as follows :



The Main thing for this post is $.Ajax with Get and Post xmlHttpRequests.
on successful response its get displayed else response received with an Error like internal server error (500) etc.

following action receives the submit for this page with an Ajax Call.

public JsonResult GetTime(string zone)
        {
            Person person = new Person();
            person.Name = "Vishal";
            person.Address = "Indore";
            return Json(person);
        }

Which returns the data in Json Format.


When I use xmlhttprequest Post in $.Ajax function of Jquery I receive the following Response.






and When I use xmlhttprequest type Get in $.Ajax function nothing is updated in Red dotted area and I receive internal server Error (500) with following Error Message as Response.

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.

Its because Json only allow Json Post(as its more secure) Request but deny Get request because confidential information can not be retrieve using get request.

but if you aware its risk and want to allow Get request for Json you can do this as follows :
return Json(person,JsonRequestBehavior.AllowGet);

in this way you can retrieve data from Get Request but its won't be secure anymore as anyone can now access this infromation by simply sending request using url.

client side validation in Asp.net mvc 2 and mvc 3

. Monday, October 3, 2011
0 comments

Hello Guys,

we all are aware about how do we validate user input for model in asp.net mvc using server side validation.
but this feature is also applicable for client side as well. its a pretty thing to hear..
So what will do the client side validation if Server side validation already over there?
well this give you very much facility as you don't need to make the whole page refresh just put some javascript libraries and they will do their job by making partial page refresh and without posting your page back.
So with this technique of validation we can validate user input without making page to post back every time and displaying the validation after the complete page Call.

Lets have a look for this pretty thing.

a)First I create a model which will need to validate for user input in our View.
 public class Person
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "First Name is required")]
        [StringLength(10, ErrorMessage = "First Name max length is 10")]
        public string FirstName { get; set; }
    
        [Required(ErrorMessage = "Last Name is required")]
        [StringLength(10, ErrorMessage = "Last Name max length is 10")]
        public string LastName { get; set; }
    
        [Required(ErrorMessage = "Email is required")]
        [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email Format is wrong")]
        public string Email { get; set; }
    }

b) create an action method in controller which will used to render View later for this model.
       
        public ActionResult Person()
          {
                return View();
          }

c)Now just need to reference some of the js libraries for client side validation to work,so for this 
  reference following js which are already in script folder into your Master Page.
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>


    Person


    

Person

<%Html.EnableClientValidation(); %> <% using (Html.BeginForm()) { %>

<%=Html.ValidationSummary(true) %>

Id:

<%=Html.TextBoxFor(x=>x.Id) %>
<%=Html.ValidationMessageFor(x=>x.Id)%>

FirstName;

<%=Html.TextBoxFor(x=>x.FirstName) %>
<%=Html.ValidationMessageFor(x=>x.FirstName)%>

LastName:

<%=Html.TextBoxFor(x=>x.LastName) %>
<%=Html.ValidationMessageFor(x=>x.LastName)%>

Email:

<%=Html.TextBoxFor(x=>x.Email) %>
<%=Html.ValidationMessageFor(x=>x.Email)%>


<%} %>


Here thing to notice is that everything is same as Server Side Validation Except one new thing is added which is
<%Html.EnableClientValidation(); %>

Which Causes the Client Side Validation.
The above scenario will look like as follows :
When someone enter the wrong value for field the validation is displayed.

          
           
 



















Now when someone enters the correct value for specified field the validation removes without causing the whole page refresh.



























Client Side Validation in Asp.net MVC 3 :

All the things are same as done with mvc 2 except the following :
a)Add the appropriate references in the master page as follows :



 

Here a New thing to note is Unobrustive Javascript library which is generally writing Html and Javascript separately.

you also need to set Unobrustive js and clientside validation in Web.config file
as follows :


 
        
     
 

both the options need to set true if you want client side validation in your application.

Hope you Enjoyed this article.