DalSoft / dalsoft-website-comments

0 stars 0 forks source link

blog/index.php/2010/04/26/mvc-2-templates/ #12

Open utterances-bot opened 2 months ago

utterances-bot commented 2 months ago

ASP.NET MVC 2 Templates | DalSoft Ltd

MVC 2 is official, I’ve been using it for a while now (since preview), my favorite feature by far is templating.

https://www.dalsoft.co.uk/blog/index.php/2010/04/26/mvc-2-templates/

DalSoft commented 2 months ago

Legacy Comments

Daniel15 says: April 27, 2010 at 4:15 am Nice post 🙂

To make the labels bold, ideally you should be using CSS instead of adding additional HTML markup. And the JavaScript (for the calendar) should be unobtrusive; the HTML source should not have any JavaScript in it other than the script references. Date fields should have a class=”date” or similar, and then some JS that runs on page load should add the calendar button.

Although I guess this post is really about ASP.NET MVC, and in that regard, it’s a great post. Nice work 🙂


DalSoft says: April 27, 2010 at 12:05 pm Thanks I completely agree with your comment. I should of used separate JavaScript/CSS files and used jQuery to select the elements by class name for example $(“.dateField”).datepicker();

The reason for not doing so is I tried to keep the steps as simple as possible, in an effort to highlight the MVC 2 template features as much as possible. Next time I’ll add a note of what should be done in a production scenario.

The only thing I’ll add to your comment is you shouldn’t rely on JavaScript alone, you should also have equivalent functionality in your server side code, for example if you are validating a date in JavaScript, you should have equivalent server side code for security and usability reasons. In MVC this can be achieved with very little code using data annotations.


Steve says: April 27, 2010 at 4:59 am Great post!

I can’t see the code in the code snippets though – just the html parts ?

Thanks again!


DalSoft says: April 27, 2010 at 12:16 pm Thanks, sorry that you can’t see the snippets though, for some reason the wordpress syntax plug-in I’m using is only working in Firefox. I’m looking into it now.


oVan says: April 27, 2010 at 6:37 am Could it be that you pasted the wrong sample code below this text “To use the built-in templates just replace the Html.TextBoxFor helper with the Html.EditorFor helper, the mark-up will look like this:”? It is identical to the snippet above it.


oVan says: April 27, 2010 at 6:49 am My previous remark is only valid on Google Chrome: about all code snippets are displayed incorrectly. I just tried it in Firefox and it looks correct. Please put a note at the start of the article (or maybe you can fix the Chrome problem?) Thank you for your interesting post! Olivier.


DalSoft says: April 27, 2010 at 12:19 pm Thanks, I’m looking into why the snippets only work in Firefox.


Daniel Eagles says: April 27, 2010 at 10:06 am Great post thank you, everything I need to know about MVC 2 in one post. For some reason though the ASP code snippets only work in firefox.


DalSoft says: April 28, 2010 at 12:38 am OK I’ve got the ASP.NET snippets working in Chrome, Firefox and Safari. It’s still not perfect as it’s not obeying the tabs. I’ll test IE7-8 tomorrow.

I’m going to look for a better syntax highlighter plug-in, any suggestions for one that supports ASP.NET properly are welcome.


coderY says: April 28, 2010 at 12:43 am Thank you so much for sharing this with us.


April 30th Links: ASP.NET, ASP.NET MVC, Visual Studio 2010 - ScottGu's Blog says: April 30, 2010 at 8:58 am […] ASP.NET MVC 2 Html.Editor/Display Templates: A great blog post detailing the new Html.EditorFor() and Html.DisplayFor() helpers within ASP.NET MVC 2. […]


Saeid says: May 4, 2010 at 1:26 pm Great post, Finally MVC2 Templates became clear to me, thanks for that


Instant Development says: May 6, 2010 at 2:19 am Great article. I have migrated a couple of apps to MVC2 and being able to rip out ugly views and replace them with a consistent UI using templating is a real pleasure. You give some great tips on using templates.


Wojtek says: May 7, 2010 at 10:03 am Hi, template explanation is great, yet I’m not able to run your example on complex types. I mange to use template for Offices and display is correct. Unfortunately it doesn’t bind selected offices to the model after post. I suppose that to bind to list of complex types I need to post form values like: Offices[0].OfficeId = “guid_1”, Offices[1].OfficeId = “guid_2”, … But dropdownlist doesn’t allow to post such values, it can post only multiple parameters having the same name (no indexing). Could you help, to make your example working? Regards.


DalSoft says: May 21, 2010 at 2:17 pm Hi Wojtek, my post on Model Binders updates the employee example, so that it displays the offices the the user selected. Hopefully this should help you.


Some neat features of asp.net mvc 2 says: May 7, 2010 at 1:06 pm […] It's difficult to get across how awesome this is without writing a whole post about it, fortunately someone's already done that for me and I can't recommend it […]


Gavin says: May 20, 2010 at 1:54 am This post is what I’ve been looking for a long time. I would love to see an example of how you would create a template for selecting the Employee’s Department.


DalSoft says: May 21, 2010 at 2:18 pm Hi Gavin, my post on Model Binders updates the employee example, so that it displays the offices the the user selected. Hopefully this should help you.


MVC Model Binders says: May 21, 2010 at 2:04 pm […] MVC 2 Templates May 21 […]


Jason says: May 30, 2010 at 4:29 pm Awesome post! Exactly what I’ve been looking for! Excellent job! Keep it up!!:) Your biggest fan here! LOL


J Dubs says: June 16, 2010 at 12:59 pm Many thanks for the detailled blog post. Having downloadable examples has really helped.

I should point out that I did have a problem with the UrlParameter.Optional reference in the global.asax file. As I’ve been playing around with this for a while I decided to uninstall all the MVC installs 2.0 & 1.0 and then reinstall the latest version. This solved my only problem.

Cheers !


Ian Turner says: July 13, 2010 at 2:21 pm I too love templates – for instance I’m writing an application form view that calls a “person” template (several times) that calls a “postal address” template several times…

However, and this is a big however, the HTML renders controls with, for each address, the same “id” attribute, say “line1” for the first address line, when in fact my model binding requires ids like e.g. “person1.homeaddress.line1”, “person2.officeaddress.postcode”…

Any suggestions very gratefully received, because at the moment I’m considering a custom version of Html.Partial that accepts a “model prefix” parameter, and pfexing the ids with that.

TIA Ian


DalSoft says: July 19, 2010 at 10:33 am Take a look at the Bind attribute using the prefix parameter, this can be used on a class or a Action’s parameter examples:

public ActionResult Index([Bind(Prefix=”MyModelPrefix”)]Foo model)  {

  return View(model);
}

[Bind(Prefix = “MyModelPrefix”)]
public class Foo {
   public string Bar { get; set; }
}

Further reading: http://weblogs.asp.net/scottgu/archive/2008/10/16/asp-net-mvc-beta-released.aspx#three

http://msdn.microsoft.com/en-us/library/system.web.mvc.bindattribute.aspx


Riddhi says: July 16, 2010 at 11:27 am Hi.. Many Thanks for your post…Its realy help me a lot…

Thank you


Carlos H says: August 11, 2010 at 6:22 pm Hi, is there a way to change the icon which appears next to the datepicker calendar? I kinda don´t like it, I´d rather put a small calendar image there for my application but I don´t know how.

Thanks.


DalSoft says: September 23, 2010 at 11:14 pm Yes change the DateTime template, add the buttonImage parameter to the datepicker function example below:

$(document).ready(function() {

 $(“<%=id%>“).datepicker({
   showOn: ‘both’,
   buttonImage: “images/calendar.gif”,
   dateFormat: ‘dd M yy’,
   changeMonth: true,
   changeYear: true
 });

});

Kevin says: August 11, 2010 at 9:58 pm What if you create an html helper extension for the EditorFor(model => model.Property, “MyCustomEditor”)

For example, you have to render a date picker, instead of call EditorFor(…) for the date picker, you call Html.DatePickerFor(…)

… DatePickerFor(…)
{
   return EditorFor(…, “DatePicker”)
}

This will keep the magic string to a minimum and is much nicer for other developers to use. What are your thoughts on this?


DalSoft says: August 12, 2010 at 10:57 am You don’t need to use magic strings with templates when dealing with non complex types, just simply name the template DateTime.ascx. For complex types you can use the DataType attribute as described in the post.

For example Html.EditorFor(model => model.MyDateTimeProperty) works when you name your template DateTime.ascx convention over configuration takes over and the template is selected using the property’s type name.

Writing your own html helper extension is a solution, but you are rendering html/javascript using code which could be problematic, for example you will need to write a helper to replace each template, rather than using simple mark-up in a template.

I personally like the flexibility of being able to change templates easily by dropping files into the DisplayTemplates or EditorTemplates folder whenever I want to change how my Model’s properties are displayed. In the end though I guess it’s a matter of taste and what works for your situation.


Daniel Liuzzi says: September 13, 2010 at 7:25 am DalSoft,

Great article with lots of useful information. A little nitpick: the preferred nugget to use in MVC 2.0 uses the colon instead of equal sign. (i.e. instead of (my apologies if WordPress strips the angle brackets). Equal sign nuggets are no longer recommended, because they are vulnerable to XSS attacks if you forget to encode your output. By using the colon instead of the equal sign, encoding is done automatically for you, so no more ugly Html.Encode()’s on your views.

Cheers.


DalSoft says: September 23, 2010 at 9:16 pm Hi Daniel thanks for your feedback.

I agree, but I wrote the examples in .NET 3.5 as I wrote this post just before .NET 4 went RTM (<%: is a .NET 4 feature). My latest update to the post uses <%:


Roberto says: October 13, 2010 at 10:12 am Great article, DalSoft! Thank you.

One problem though: when I supply an instance of EmployeeModel to the View, an exception is raised:

The model item passed into the dictionary is of type ‘System.Int32’, but this dictionary requires a model item of type ‘System.String’.

I would expect the Int32 property to default to the default editor (i.e. the build in editor).

[HttpGet]
public ActionResult Index()
{
   return View(
      new EmployeeModel
      {
         Id = 12
      });
}

Btw, is it possible to override the selection of templates. It would be nice if various datetime pickers could be used (depending on the user’s preferences).

Ciao


Ranco says: October 15, 2010 at 12:12 pm The first template (partial view) is inherited from ViewUserControl.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl” %> …

However, the String template is not only used for strings, but for all simple types (if not overridden).

See the tutorial ‘ASP.NET MVC 2 Templates, Part 3: Default Templates’ at http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html and especially Richard Folland’s comment.

Removing the generic argument from the first line of the template resolves this issue.


Marshall says: November 23, 2010 at 8:10 pm What if you wanted to add to the list of Offices instead of selecting an existing one on the same view? How do you display a text boxs for Office Address and Country?

Thanks, -Marshall


Some links for 2011-05-20 at The Standard Output says: May 20, 2011 at 7:28 pm […] Blog jQuery plugin: Tablesorter 2.0 DataTables (table plug-in for jQuery) jQuery Grid Plugin ASP.NET MVC 2 Templates Take a Mulligan with Redo Backup & Recovery | Linux Magazine http://www.Visual6502.org MetaSharp […]

Gene Osteen says: September 21, 2011 at 9:00 pm I’m stuck at trying to add the calendar. I keep getting the below error every time I add the DateTime View to the Editor Templates. when I remove the view everything works fine.

{“The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type ‘System.DateTime’.”}


swapna says: April 20, 2012 at 2:08 am wow!! such a great article!!!


narasimha says: April 9, 2013 at 6:23 am Excellent article. You can publish a book with such excellent content


Cody Sternberg says: February 4, 2014 at 3:17 pm You have a great blog right here! With content like this you should write a MVC book.


henkel-partner.net says: July 15, 2014 at 12:32 pm Hey there, I think your website might be having browser compatibility issues. When I look at your website in Firefox, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, excellent blog!


superiorbhb says: October 12, 2019 at 8:21 am Great Information.Thanks for sharing 🙂