eWorld.UI - Matt Hawley

Ramblings of Matt

Using SubDataItems and View User Controls in ASP.NET MVC

June 4, 2008 08:46 by matthaw

Prior to the preview 3 release of ASP.NET MVC, whenever you wanted to pass data to your view user controls, you only had the option of passing a specific object, or using it's parent's view data. This was all great, and it worked wonderfully, but the problem existed that your view user control would always be dependant upon some parent view data. ASP.NET MVC preview 3 introduced the concept of SubDataItems off of ViewDataDictionary in which you could specify a keyed ViewDataDictionary to use. This helps in the true separation of your view user controls, or child views, and will hopefully later lead into more interesting solutions such as sub-controllers. So lets get into an example.

Hold It! Yeah, we have to patch the MVC framework first before doing anything further. I've logged a bug with the ASP.NET MVC team regarding this, and it's unfortunate to say that this shouldn't have slipped through - but that's what you get without test cases. But I digress. Okay, open the MVC Preview 3 source and open the file "System.Web.Mvc/Mvc/Extensions/UserControlExtensions.cs". Go to the "DoRendering" method, and replace the if block starting on line 127 with the following:

   1:  if (controlData != null) {
   2:      instance.ViewData.Model = controlData;
   3:  }
   4:  else if (!string.IsNullOrEmpty(instance.SubDataKey)) {
   5:      instance.ViewData = context.ViewData.SubDataItems[instance.SubDataKey];
   6:  }
   7:  else {
   8:      instance.ViewData = context.ViewData;
   9:  }

 

Okay, onto the example. Say you have a product detail on your website, and you need to display the product information on the listing page as well as on the order summary page. Because we want to display the same information in the same way on each page, it leads us into using a ViewUserControl. There's other information listed on each page itself, so there is definitely no need to create or duplicate our view data model object just for display purposes. First, we should define our model.

   1:  public class Product
   2:  {
   3:      public Product(int id, string name, decimal price)
   4:      {
   5:          Id = id;
   6:          Name = name;
   7:          Price = price;
   8:      }
   9:   
  10:      public int Id { get; set; }
  11:      public string Name { get; set; }
  12:      public decimal Price { get; set; }
  13:  }

Next, let's work on our controllers. To show the true separation, I'll have both a ProductController and OrderController.

   1:  public class ProductController : Controller
   2:  {
   3:      public ActionResult Index()
   4:      {
   5:          ViewData["Category"] = "Bicycles";
   6:          ViewData["SubCategory"] = "Mountain Bikes";
   7:   
   8:          Product product = new Product(1, "16 Speed", 499.99m);
   9:   
  10:          ViewDataDictionary<Product> subViewData = 
  11:                    new ViewDataDictionary<Product>(product);
  12:          subViewData["ShippingCost"] = 24.99m;
  13:          ViewData.SubDataItems.Add("ProductData", subViewData);
  14:   
  15:          return View();
  16:      }
  17:  }
  18:   
  19:  public class OrderController : Controller
  20:  {
  21:      public ActionResult Index()
  22:      {
  23:          Product product = new Product(1, "16 Speed", 499.99m);
  24:          decimal shipping = 24.99m;
  25:          decimal tax = (product.Price * .08m);
  26:          decimal total = product.Price + shipping + tax;
  27:   
  28:          ViewData["OrderAmount"] = product.Price;
  29:          ViewData["Tax"] = tax;
  30:          ViewData["Total"] = total;
  31:   
  32:          ViewDataDictionary<Product> subViewData = 
  33:                     new ViewDataDictionary<Product>(product);
  34:          subViewData["ShippingCost"] = shipping;
  35:          ViewData.SubDataItems.Add("ProductData", subViewData);
  36:   
  37:          return View();
  38:      }
  39:  }

As you can see, within both of the controller actions, I'm creating a new instance of a ViewDataDictionary<Product> and adding it to the ViewData.SubDataItems. This will allow me to later extract that specific ViewDataDictionary when rendering the ViewUserControl. Granted, this scenario is very rudimentary - but I wanted to show that each action / view has it's own data, but wanted to show the "sharing" of the SubDataItem data. Now, we implement our ViewUserControl (I won't show the HTML for this, it's in the download though). The ViewUserControl simply needs the following

   1:  public partial class ProductInfo 
   2:          : System.Web.Mvc.ViewUserControl<Models.Product> { }

Now, in both our Index views for product & order  we can call the helper method to render our view user control. Please note that within this, we're not specifying any control data (model) but we are specifying the SubDataKey. As you've probably figured out, that SubDataKey is the key the framework uses to extract the correct ViewDataDictionary to set on the ViewUserControl when rendering. Should you not specify a SubDataKey, it'll use the parent ViewDataDictionary - so in this case, our ViewPage's ViewDataDictionary.

   1:  <%= this.RenderUserControl("~/views/shared/ProductInfo.ascx", 
   2:                             null, 
   3:                             new { SubDataKey = "ProductData" }) %>

And that's it. Of course, SubDataItems can be used for other purposes like keeping your ViewData "componentized", but the best use for this so far is so that your ViewUserControl's can live without the knowledge or sharing of parent ViewPage's or ViewUserControl's. If you'd like the source for this demo, you can download it here. It already has the patched MVC assembly. Enjoy!

kick it on DotNetKicks.com


Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

June 6. 2008 07:07

Pingback from weblogs.asp.net

Using SubDataItems and View User Controls in ASP.NET MVC - eWorld.UI - Matt Hawley

weblogs.asp.net

June 13. 2008 00:34

Very cool. I was trying to enable a scenario like these were designed for without knowing about them... I got it working, but it wasn't as clean as I would've wanted. Looks like the fix is here. Smile Much appreciated.

paul

December 5. 2008 19:56

hgj

b

February 14. 2009 15:16

hi,

i thank you for your post. I have another sceniro for example i have to show five textboxes in an web page, each textbox should come from an xml document. Depending upon the user i should make each textboxes visible,hidden,readonly,change the order. Kindly give an idea how to do and given some sample coding to start.

thanks in advance

regards,
senthil

senthil kumar

June 1. 2009 23:35

Nice article

yazılım

June 2. 2009 16:23

Thank you great turtorial..loved that

Definition

June 12. 2009 05:11

Thanks regards

commercial deep fryer

July 2. 2009 10:48

Thanks loved info.

meaning

July 2. 2009 10:49

nice turtorial

define

July 4. 2009 14:53

very good tutorial thanks for sharing

Lap band

July 4. 2009 14:56

thanks for the post.it helped me a lot

Surgical instruments

July 18. 2009 22:49

Thank you for useful information was a good article

sex movies

July 20. 2009 15:59

thanks you

Porno izle

July 22. 2009 12:16

Nice article.

Nutrition degree

July 22. 2009 12:17

Thank you great turtorial.

BS degree

July 22. 2009 12:17

great post.

Project management diploma

July 22. 2009 12:17

Looks like the fix is here. Smile Much appreciated.

Economics degree

July 22. 2009 12:18

I got it working, but it wasn't as clean as I would've wanted.

Teaching degree

July 29. 2009 13:36

I'd say it's pretty trivial, actually.

Custom Thesis

July 29. 2009 13:36

I think this is a good point. thanks for the great article, this really nice blog.

Resume Writing Services

August 2. 2009 08:59

hi all.
thank too the apple. http://www.germanporn.tk

Porno filme

August 2. 2009 09:00

Thanks a lot for this scripot.I have been looking for it for a long time http://www.tvsexizle.com

Porno izle

August 9. 2009 08:18

Learn how to use the new SubDataItems within the ASP.NET MVC Preview 3 bits with your View User Control. Also explains a small patch to the framework to get this to work correctly

play free casino slot machines online

August 9. 2009 11:01

Thank you great turtorial..loved that

tiffany

August 12. 2009 07:31

Its the post i really looking for i like to blog and i want to be a member of this thanks for post.
Regards,

Essay Help

September 18. 2009 01:33

Very interesting post. Might be old, but it was new to me. Good thing you have come up with such blog. I thought it was going to be some boring old post, but it really compensated for my time. Nice blog. I just bookmarked it for later reference. Good job.

Buy Research Papers

September 20. 2009 20:12

Tested, and Working! Thanks so much buddy. This really helped me alot since i badly needed this for my thesis project. Looking forward for more updates on this.

wow power leveling

September 20. 2009 22:53

We need to learn more from this. These a are just simple codes but it can really make business processes more efficient. Thanks for sharing this very useful information.

PhD Dissertation

September 26. 2009 02:28

Hi,
Dry Cough, X ray clear, all home based remedies tried?

XRF

September 26. 2009 14:18

I believe this new ASP.NET MVC preview 3 will really solve a lot of problems of the older versions. The possibilitys for sumneus are imense and they could ease the job alot.

Free Internet Advertising

October 3. 2009 21:55

Thanks for sharing such a wonderful piece of information with us, it will help a lot.

Term Paper

October 6. 2009 10:52

Very cool. I was trying to enable a scenario like these were designed for without knowing about them... I got it working, but it wasn't as clean as I would've wanted. Looks like the fix is here. Smile Much appreciated.

auto insurance

October 7. 2009 05:20

I am surprised they let something like that slip through. Good thing you found it and reported it though! Now I know why one of my programs isn't working right. Just fixed it.

drug addiction relapse

October 8. 2009 09:40

4RX is an online pharmacy to Buy Viagra online. Buy cheap generic drugs like Sildenafil (GENERIC VIAGRA) online and Generic Levitra Online.

Buy Viagra

October 9. 2009 03:59

i have also tested this and it went good. Thanks for the great information.

Adapter

October 9. 2009 04:04

this is so good. This information is so good. This will definitely help me in the future.

Auto

October 9. 2009 18:49

i have also tested this and it went good. Thanks for the great information.

live score service

October 9. 2009 18:49

Very cool. I was trying to enable a scenario like these were designed for without knowing about them

kamagra

October 9. 2009 18:49

We need to learn more from this

cheap kamagra

October 9. 2009 18:50

Tested, and Working! Thanks so much buddy

viagra distributor

October 9. 2009 21:58

Thanks for a great tutorial, very helpful with this bug. thanks

Colon Cleanse

October 10. 2009 13:38

Learn how to use the new SubDataItems within the ASP.NET MVC Preview 3 bits with your View User Control. Also explains a small patch to the framework to get this to work correctly.
Emo

Emo

October 12. 2009 17:40

I didnt know SubDataItems can be used in this way.
Thank you

Property Sales CRM

October 13. 2009 21:11

Using ASP.NET is not that easy. i am also student of ASP.NET. Articles here are really assisting me to learn.

Bollywood Tour

October 14. 2009 13:40

Well done you! I respect the musicians. This is a creative person. Good luck!

PhD Dissertation

October 14. 2009 18:55

Searching for this for some time now - i guess luck is more advanced than search engines Smile

Cash Advance

October 16. 2009 11:34

we have to patch the MVC framework first before doing anything further. I've logged a bug with the ASP.NET MVC team regarding this, and it's unfortunate to say that this shouldn't have slipped through

games

October 16. 2009 17:39

great

vigrx plus

October 16. 2009 18:17

Tested, and Working! Thanks so much buddy

free online games

October 20. 2009 09:08

Wonder full writing skills you got mate.


Regards
Joini

natural pool designs

October 20. 2009 23:36

GOOD JOB,I like it!

ed hardy

October 21. 2009 00:18

[url=http://www.edhardysell.com]ed hardy[/url],Can you tell me?

ed hardy

October 21. 2009 00:53

Thank you for the tutorial, I really appreciate your efforts.

Debra

Medela Symphony

October 22. 2009 02:07

I can't help but think this is a good thing, it's about time wealth was distributed a bit more evenly.

Persuasive Essay

Comments are closed

Copyright © 2000 - 2010 , Excentrics World