Is there any way to add class to input using FluentBootstrap? - asp.net-mvc

#form.EditorFor().AddAttributes(new {#class="class"}) makes a div wrapper with added attributes, is there any way to actually add class to input itself instead of wrapping it around?

Sorry it took so long for me to find this - still not used to coming on StackOverflow and searching for my libs :).
Unfortunately, you can't do what you want to at this time. As far as I know, you wouldn't be able to do it in straight ASP.NET MVC either.
The problem is that calling EditorFor() really just farms out to an editor template (Scott Hanselman has a nice little real-world example on his blog). Depending on the model property type, the editor template could have an <input>, or it could have a <textarea>, or it could have a whole bunch of form elements for a really complex editing experience. Since we don't know what the EditorFor() might return, we have no way of knowing to which element, or even if, the extra attributes should be applied.

Related

Reading Form Post data vs strongly typed View

I have a set of HTML pages containg input elements. I am in the process of converting them into MVC Views.
Considering performance & cleanliness of code. What is the correct way to proceed,
Processing Form as posted FormCollection, or
Create Strongly typed view to obtain input values from the Model.
One advantage of using HTML helpers is it enables better compile-time checking of your views (allowing you to find errors at build-time instead of at runtime), and also supports richer intellisense when editing your view templates within Visual Studio.
Another advantage might be HTML helpers allows you to set any custom attributes on the HTML tag. You can do that with the helper by either passing in a dictionary or using an anonymous type like following.
#Html.TextArea("FirstName", Model.FirstName, new { parameter = "value" });
Source 1
Source 2
You can use an overload of TextBoxFor to set/override the input element attributes:
#Html.TextBoxFor(m => m.Name, new { #Value = "0", readonly="readonly" #class="cssClass"})
This is actually a good question..I don't know who voted it down...there are too many strict view model evangelists in my opinion.
After Having worked with MVC for awhile my view is that for very simple things the #Html helpers work very well...however they lead to a way of thinking about the webpage/server interaction that is limiting in the long run, especially for more complicated uses. It lets you rely heavily on unobtrusive validation without having to understand how validation works on the client..this is great for the introductory programmer...as I once was...however not understanding at least the jquery validation libraries will handicap you eventually. Doing any serious web/web-application development where validation is more complicated than checking if a value is required becomes much more diffucult. In addition you are relying on Microsoft to keep their validation library in sync with the jquery validation libraries should you update them(I've ran into this issue).
In addition you need to consider what if any front-end libraries you are using and if any of them don't work well with the output of these helpers(bootstrap is one notable one). That being said form collection is faster and less restrictive...using it and the pure validation libraries will be easier and more expressive...letting you write whatever code you want. After all..how hard is it to write if(!String.IsNullorEmpty()) on the server-side or whatever type of validation you need in addition to the client.

Why is System.ComponentModel.DataAnnotations.DisplayAttribute sealed?

I was going to implement a custom DisplayAttribute in order to allow dynamic display values based on model values, but I can't because DisplayAttribute is sealed.
Before I go off and write my own customer attribute that emulates the behavior of DisplayAttribute, can anybody think of why this is sealed? I'm assuming there is a reason behind it, and if so, that may be the same reason I shouldn't try to "hack" around this limitation by rolling my own.
I'm not asking anyone to read Microsoft's mind, I'm just hoping someone already knows the by-design reason it's sealed, so that I can take that into account when rolling (or avoiding) my own implementation.
In general it is considered best practice to seal attributes. FxCop has a rule about it, defined here. From that page:
The .NET Framework class library provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy; for example Attribute.GetCustomAttribute searches for the specified attribute type, or any attribute type that extends the specified attribute type. Sealing the attribute eliminates the search through the inheritance hierarchy, and can improve performance.
Many of the MVC attributes (ActionFilter, etc) are unsealed because they are specifically designed to be extended, but elements in the DataAnnotations namespace are not.
Not exactly what you asked, but following your intent...
You can still allow for dynamic display values, you just wont extend the DisplayAttribute.
Instead, you can implement your own IModelMetadataProvider which could contain any logic needed to create dynamic display values.
Brad Wilson, from the ASP.NET MVC team, has a good article and sample of this on his blog: http://bradwilson.typepad.com/blog/2010/01/why-you-dont-need-modelmetadataattributes.html

Should the model be responsible for holding lists that will ultimately populate dropdownlists in the view?

This might be similar to ASP.NET MVC - Populate Commonly Used Dropdownlists.
I want to populate DropDownLists. Some of it is static data. Some of it comes from the Database. A couple of times I found myself forgetting to call the code that populates my lists and sets the ViewBag accordingly. It is almost worth adding a unit test for this. The only way I think that this suits a unit test is if you place it in model/service. Is there a best practice for this kind of thing?
I'd suggest that the data is contained within the model but is perhaps constructed by a html.helper method. this way, you keep the plumbing markup out of the view and leave the controller free to invoke the neccesary view and model.
You could also of course hand it off to a partialview with an <IList<SelectList>> model.
cats and their skin :)
If you follow the spirit of the pattern then the Model should supply the View with everything it needs to present to the user that's not static. If you have static dropdown lists then you could say that these could be constructed within the mark-up. If you are passing a SelectList to the View from your Action then I'd stick it in the Model to make things simpler and more coherent.
My rule of thumb is that the data must somehow be in the model, either as a ready to use SelectList or at worst in some container that can easily be turned into a SelectList using a LINQ-to-object call.
The bottom line is that the view should never contain any non trivial code.
EDIT (answer to your comment):
I try not to put too much code in models. Models are more like a simple bunch of data gathered by the controller and used by the view.
Regarding simple and/or common things such as the days of week, I believe an HTML helper is the most elegant solution. See WayneC's answer in this question.

When is it right to use ViewData instead of ViewModels?

Assuming you wanted to develop your Controllers so that you use a ViewModel to contain data for the Views you render, should all data be contained within the ViewModel? What conditions would it be ok to bypass the ViewModel?
The reason I ask is I'm in a position where some of the code is using ViewData and some is using the ViewModel. I want to distribute a set of guidelines in the team on when it's right to use the ViewData, and when it's just taking shortcuts. I would like opinions from other developers who have dealt with this so that I know my guidelines aren't just me being biased.
Just to further Fabian's comment; you can explicitly ensure viewdata is never used by following the steps outlined in this article. There's really no excuse not to use models for everything.
If you have no choice but to use ViewData (say on an existing project); at the very least use string constants to resolve the names to avoid using 'magic strings'. Something along the lines of: ViewData[ViewDataKeys.MyKey] = myvalue; Infact, I use this for just about anything that needs to be "string-based" (Session Keys, Cache Keys, VaryByCustom output cache keys, etc).
One approach you may wish to consider as your views become more complex, is to reserve the use of Models for input fields, and use ViewData to support anything else the View needs to render.
There are at least a couple of arguments to support this:
You have a master-page that requires some data to be present (e.g. something like the StackOverflow user information in the header). Applying a site-wide ActionFilter makes it easy to populate this information in ViewData after every action. To put it in model would require that every other Model in the site then inherit from a base Model (this may not seem bad initially, but it can become complicated quickly).
When you are validating a posted form, if there are validation errors you are probably going to want to rebind the model (with the invalid fields) back to the view and display validation messages. This is fine, as data in input fields is posted back and will be bound to the model, but what about any other data your view requires to be re-populated? (e.g. drop-down list values, information messages, etc) These will not be posted back, and it can become messy re-populating these onto the model "around" the posted-back input values. It is often simpler to have a method which populates the ViewData with the..view data.
In my experience I have found this approach works well.
And, in MVC3, the dynamic ViewModels means no more string-indexing!
I personally never use ViewData, everything goes through the Model, except when im testing something and i quickly need to be able to see the value on the view. Strongtyping!
In terms of ASP.NET MVC 2, ViewModel pattern is the preferred approach. The approach takes full advantage of compile time static type checking. This in combination with compiling mvc views will make your development work-flow much faster and more productive since errors are detected during build/compile time as opposed to run time.

is there any legitimate reason to use ViewData in asp.net mvc

with model binding where you can build up an object to ship and bind to the view, is there any reason to ever use ViewData ?
I can't forsee an instance where I would use it unless I had static information coming in from a database for a page/master that then got displayed in say a <p> or some such.
If the page was a read only page that say returned a list of items and I also wanted to display text from a DB then I might use ViewData.
But that's kind of an exception. If I was returning a list of items from a DB along with some other stuff then I would create a Form View Model and simply include any other data in with it.
So rarely I guess is my answer here.
ViewData seems to exist as a simple, convenient approach to something that you really should do a syntactically cleaner way. The MVC equivalent of an ArrayList I suppose- works just fine but you'd be hard pressed to come up with a truly legitimate excuse for using it in good code.
One exception I can think of for using it would be including something dynamic in ALL of your pages that gets appended in an ActionFilter or base Controller class- for example "WebsiteTitle". Rather than attempting to tamper with the data being returned by a Controller action it might make more sense to include something like that in the ViewData collection- perhaps prefixed with some unique identifier to make it obvious it was being included outside the controller action. ViewData["Base_WebSiteName"], for example.
I am pretty new to MVC but what little I have done, I have written custom objects for all my views.
The only reason I could think of is to save time. You need to whip something up fast and maybe there are multiple objects of data on a page and something extra and you don't want to take the time to write an object putting it all together. Is this a good reason? In my opinion no.

Resources