Monday, June 11, 2012

Display Label for your model in View

Let's see what was annoying in old fashion aspx pages before and how MVC helps us to overcome it.
Consider you want to show the "Product Name" as a label in some pages in aspx pages , there was different possibilities to achieve it , best way to create a usercoontrol for the product and add a label "Product Name" yes it it , but what if you want to show product name in other places as well like another control or another page, yes you need to write it again, this is a simple example but when it comes into a complex project maintaining this simple thing could be a nightmare.

I remember once in our company somebody mistakenly name a label "Blah blah" just for testing and that code mistakenly went into the production, but If we defined these labels in our model level, if you name something wrong you can easily change it in one place and there is more possibilities to catch it sooner at least not on production 


Model----------
public class MyModel
{
    [DisplayName("Product Name")]
    public string ItemName{ get; set; }
}

 View-----------
This is so basic and interesting of using Model metadata.

Using JSON response in JQUERY in MVC

I've found that using JSON in MVC is very handy and useful , Consider you have a template of a usercontrol/control and when an event triggers on the page you want to load the new data in your control, there are many ways to do it , one of the good ways is returns the usercontrol/control with new data completely on the page and add it again and also remove the previous one, but a question is when you already have the userontrol/control on the page and only difference is showing new data on it do you think a faster is just to load the new data and bind it into the usercontrol/control? for sure yes it is.

loading the data and bind it to your control can be handle in different ways as well , but I like JSON  format better.

Let's start calling a controller to return a simple int[] but in JSON format and see how it works.

Consider we have a method in our any controller such as PersonController to return a list of person and use it in the VIEW.

model------
public class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public int PersonID { get; set; }
        }

controller--------
 [HttpPost]
 public ActionResult GetPeople(string CountryCode)
   {
            List<Person> people=new List<Person>();
          
            for (int i = 0; i < 10; i++)
            {
                people.Add(new Person() { FirstName = string.Format("Name-{0}",i),LastName =  string.Format("Family-{0}",i),PersonID = i});
            }

            //creating a JSON response format , so you can see the "res" object
            JsonResult res = Json(people);
            return res;
  }

Now  you have an action which returns a list of person in JSON format, the only thing is call this action via JQUERY and read it and bind it to your object, since my focuse on this exercise is just to read JSON format data with JQUERY , I'm not talking about the specific control you may need.

Consider an event in your page triggers(like clicking on btnRefresh) and you want to call GetPeople action , this Action may need some parameters like CountryCode
NOTE: when you are calling $.post you are able to specify the format of the data you expect after defining the action parameter , here for this example sine I know the action returns JSON data format, so in $.post we should specify the 'json' as data format of the response.

JQuery in your VIEW

    $(btnRefresh).unbind("click").click(function() {    

        $.post('Person\GetPeople', { CountryCode: 'en-US'}, function(data) {
           //data is people
            $(data).each(function(index, person) {
               
                //alerting people info or you can repopulate your specific control based on this data
                alert('FName:' + person.FirstName+ ', LName:'+person.LastName+', PersonID:'+person.PersonID.toString() );
                         });

      }, 'json');

    });

Tuesday, June 5, 2012

MVC - UserControl and passing data from a page to it

Using UserControl makes your application pretty powerful, because you can reuse some stuff that you already created easily.

In MVC , View talks with controller to return Model as data. this is a general concept in MVC and I dont want to discuss about lots of possibilities we may have in .


Let's start creating our UserControl on PartialView in MVC , Consider we want to put productDetail information in a usercontrol and then wherever we need productInfo then easily use our existing usercontrol.

View----------------
1- Add a folder under View and name it Product.
2- Add a PartialView(UserControl) name it ProductDetailInfo.ascx.this is a strongly typedusercontrol means if you see it is inheriting from ProductModels.ProductInfo , if it was not inheriting from anything it was not strongly typed then you can not say Model.ID then you needed to use ViewData["ProductInfo.ID"]







3- Add a View(Page) name it Detail.(just need to put ProductDetailInfo.ascx. into the page.) the name if the page is the same as the controller method name in productController or in the productController when it wants to return the data we could specify the view to return as well.
in the page just add the following line to add usercontol into the page
This page is responsible to get the data and pass the required data to the usercontrol. in this example it passes all model to the usercontrol.











Controller---------
1- Add a controller class for product name it ProductController.
2- Add a new Method in the class with the following structure
public class ProductController : Controller
{
 public ActionResult Detail(int productID)
{
 ProductModels.ProductInfo productInfo = new ProductModels.ProductInfo();

  productInfo.Price = 18;
   productInfo.ID = 1;
   productInfo.Name = "Monitor";
  return View(productInfo);

  }
}


Model-----------
1- Add a new Model name it ProductModels
2- Add a new Class into it wit the following info

    public class ProductModels
    {
        public class ProductInfo
        {
            public int ID { set; get; }

            public string Name { set; get; }

            public int Price { set; get; }
        }
    }


Now Its time to press F5 and see what you have done.