Is there a specific reason why I should be using the Html.CheckBox, Html.TextBox, etc methods instead of just manually writing the HTML?
<%= Html.TextBox("uri") %>
renders the following HTML
<input type="text" value="" name="uri" id="uri"/>
It guess it saves you a few key strokes but other than that. Is there a specific reason why I should go out of my way to use the HtmlHelpers whenever possible or is it just a preference thing?
Another benefit is that if your ViewData contains a value matching the name of the field it will be populated.
e.g.
ViewData["FirstName"] = "Joe Bloggs";
<%=Html.TextBox("FirstName") %>
will render
<input type="text" value="Joe Bloggs" id="FirstName" />
There are huge benefits:
It has overloaded methods to pre-populate the values (formatted, and safe for HTML) just like the ViewState.
It allows built in support for the Validation features of MVC.
It allows you to override the rendering by providing your own DLL for changing the rendering (a sort of "Controller Adapter" type methodology).
It leads to the idea of building your own "controls" : http://www.singingeels.com/Articles/Building_Custom_ASPNET_MVC_Controls.aspx
One thing is for consistency...I for one always forget the name attribute. Plus, you can extend the functions for your own projects. They're not called helpers for nothing!
The upside to using an abstraction layer is future proofing your code in a pluggable way. Maybe today, you create HTML 4 pages but tomorrow you want to create XHTML pages or XAML or XUL. That's a lot of changes if you just hard code the tags everywhere, especially if you've got hundreds of pages. If everything is calling this library, then all you've got to do is rewrite the library. The downside is that it is usually considered to be slightly less readable by humans. So, it most probably increases the cognitive demand on your maintenance programmers. These advantages and disadvantages really have nothing to do with MVC.
It actually auto populates your textbox based upon first your ViewData.Model.uri and second by ViewData["uri"]. Doing it manually you'd need to do <input value="<%Html.Encode(ViewData.Model.Uri"%>" />
I haven't been doing MVC too long, but I've already written some extension methods to generate menu tabs based on Html.ActionLink. It allows me to be consistent with my usage and, if I decide to change how my CSS menus work, only modify a single method to output the new tab format.
The other use that I have made of them is in conditional output using ViewData to supply values to the controls.
Related
So I'm converting a WebForms application into ASP.NET MVC 4 and I would like to make sure that I'm making correct coding choices and assumptions.
1). Is the MVC equivalent of a user control a partial view?
2). In an aspx page you have a control like
<asp:Label id="X" runat="server">
with the following code in the code behind:
X.Visible = some_condition ? true : false;
Ok so, for MVC is this code equivalent?
View:
<label id="X" style="display: #Model.IsViewable">
Model:
IsViewable = some_condition ? "inline-block" : "none";
1.) Well, kinda, sorta, but no not really. Very different things - a detailed explanation would be lengthy.
2.) Equivalent maybe, but not really a good thing to do. Your model should contain data only. But yes, you can use this data in your razor views to conditionally do things including show or not show things. However, putting the css strings straight into your model data is klunky at best as well as it's usually a good idea to avoid inline styles whenever possible. IsViewable as a boolean would be better, and you can still handle showing or hiding elements (in a different way).
Example, i made a form like this
<form name="register" method="post" enctype="multipart/form-data">
<p><h3>User check</h3></p>
<p>admin ID: <input type="text" name="userid"></p>
<p>admin Pass: <input type="password" name="password"></p>
<input type="submit" name="apply" value="Submit"></p>
<p> </p>
</form>
and my manager wants to change this form to rails form template like this,
<%= form_for(:model) do |form| %>
<p>
<%=form.label :input%>
<%=form.text_field :input, :placeholder => 'Enter text here...'%>
</p>
<%end%>
My question is, it works fine with html based front code. Why do i have to change this to rails code? I just want to keep my front-end code...I don't know why i have to change this :(. Also, I'm new on Ruby on Rails. That is the main reason. I dont' want to change the existing code, if it is working.
I really hate this job. I have to translate all the attributes to the rails code and that makes me really exhausted :(
Form builders are here to help
Form helpers are supposed to make your life simpler. They are quicker to write than their pure html alternative, provided you don't write pure html first.
They also provide a lot of easy implementations for difficult integration pieces, like :
displaying a date selection select group
mirroring the fact that a check box has been unchecked in POST params
automatically adding multipart param on form if you add a file input (not actually difficult to achieve, but easy to forget)
... and many more
Further development
All of this is about comfort, and you may think you could avoid it if you already have a perfectly working pure html implementation.
But what happen if someone later has to add a date select input in your form ? She will have to use the rails helper, since it saves a lot of time in controller part to set date in database. But she won't be able to leverage form builder, since you haven't used it.
Now, she has to choose between using a non builderdate_select tag mixed in pure html or ... to rewrite your form completely. As you may realize, mixing different styles is generally considered ugly, and we don't like ugly in ruby.
Security
Form tag helpers also provide an important security measure : CSRF protection. Every time you use a rails helper to create a <form> tag, it automatically adds an hidden input containing a secret key. That key has to be posted with form data to prove request originated from current website.
If you use plain html forms, you won't have this security. You could of course add the token manually using the correct method, but this would again be more time wasting than simply using form helpers.
Bottom line
The main problem is that you write pure html before using rails helpers - that is what is wasting time.
Some benefits of using Rails form helpers are:
Consistent naming of input elements names and ids
i18n support for labels
generated URL with form_for is less error prone
Better handling of checkboxes
Nice helpers like options_for_select
Less typing
That last ones might be my favourite: less typing.
I have an (as yet) simple Spring 3 MVC web-app using JSP as the view technology. I am considering rewriting it in Grails before I get too far along.
One thing I like about Spring is the "form" tags provided in the spring-form.tld tag-library. Given a model property "myFormModel" with the "myProperty" property, this allows me to write something like: -
<form:form commandName="myFormModel">
<form:input path="myProperty" cssErrorClass="error"/>
The key here is that the form:input tag automatically does all the binding to the property in the command object, so generating (roughly) in HTML: -
<form>
<input type="text" name="myProperty" value="xyz"/>
Spring MVC will bind the form parameters to the class and pass the object to the controller. Less to go wrong.
(Please excuse the JSP and HTML, it's indicative, possibly slightly incorrect)
As I understand the GSP form tags: -
<g:form name="myForm" url="[controller:'myController', action:'foo']">
<g:textField value="${myFormModel.myProperty}" class="${...blah to select error}"/>
I cannot specify a "path" attribute: I must manually generate the name. When the path becomes complex (say a property of a item from a list), this can become hairy and noisy.
I cannot automatically specify both "normal" and "error" CSS classes: I must put EL into the <input> class attribute. Messy!
I must admit I am surprised that GSP is (what I consider) behind Spring, I thought it was all about making the obvious things simple and the hard things possible. Easy-to-read/implement forms would seem a no-brainer.
So, my questions: -
am I missing something?
should I (and can I) use the spring-form.tld in my GSP?
It makes me wonder what other gotcha's I will run into...
The beanFields plugin does everything the Spring form tags do and more. It makes working with forms about as concise as possible.
What is a good approach in ASP.NET MVC for implementing a complex form where sections of the form are shown and hidden based on a user's inputs?
My background is in Webforms. I am frequently asked to build forms where a user selects an option from a dropdown list, triggering a handful of new fields to appear. A different selection might cause a different set of fields to appear.
In the past, I would handle this scenario via an UpdatePanel and a wrapper Panel around the fields that I want to show or hide. Validation is automatically disabled when the fields are hidden.
Going forward, I'd like to make use of MVC's attribute-based model validation, but is it possible to make the validation conditional on the values of other properties?
Also, how can I handle the toggling of blocks of form fields? I know how to do it manually in jQuery, but I'm hoping there's an approach that ties in with validation and server-side code.
I am liking MVC much better overall, but I haven't figured out how to handle this type of scenario very well. Likely I just need to shift my thinking to fit better with the MVC approach.
Josh,
The first thing I's suggest is to make sure you use ViewModels for the pages that are mode complicated. A ViewModel is basically a Model you create for a specific View; for example, a ViewModel could be a composition of other classes.
As for dynamically changing the fields on your View, the best way is to use jQuery (or any other javascript library) to do it.
I also migrated from a web form environment and I know is difficult to change gears at the begining, but trust me, doing a simple jQuery even handler is much simpler than having to put in place a control panel and then the event handlers.
Not to mention that is much more efficient; update panels are after all making partial posts to the page, sometimes, with jQuery you don't even need to do that.
After a few projects with MVC, I actually now find it time consuming to go and do the Update Panels on web forms ;)
Hope this helps,
-Covo
I know this might not be the answer you're looking for, but I personally don't think complex forms are very user friendly in the first place and I always try to split them up into simpler forms where possible, or to simplify the form. I've come across many forms in websites where there are a raft of "fields" where there should really be a few questions for the user to answer. Simple stuff which gets to the point of what they want to achieve rather than the field values, along with a lot of application specific knowledge needed to set those fields to the right values.
If you still want to go ahead with a complex form, then as the other answers have already stated there are facilities provided by MVC to do that, but there isn't any set way. So, it's down to you to figure out what will work best for your users.
Traditional asp.net webforms did alot of "magic" for you whereas you have to be aware of the work that goes into creating the "magic" in asp.net MVC. The benefit is that with MVC you have more control over what is happening which can also enhance performance.
In asp.net webforms an UpdatePanel is used for ajax calls. If you need to got to the server asynchronously(without doing a full post back) then use ajax via JQuery. See below for example:
$.ajax({
type: "get",
url: "/YourController/YourAction",
success: function (obj) {
//any logic you want to do upon success
}
});
The above example will do an ajax HTTP GET call to /YourController/YourAction.
In order to handle "toggling of blocks", if you don't need to go to the server for data and you simply want to do it on the client, then use simple jquery. JQuery has a function for toggling items.
http://api.jquery.com/toggle-event/
Because of the way MVC works in contrast to Webforms you're stuck with the responsibility of really thinking about what happens on the client and what happens on the server separately as not a lot of meta-data is being passed back to give us that happy Webforms feeling.
However, there is a notion when using the built-in AJAX libraries when you render a form that you can have it auto do an update once it is posted. In a sense, it's saving you the JavaScript/JQuery because it "auto-wires" it up similar-ish to a Panel. In this way you could potentially look at progressively rendering your complex forms from the server as each section is edited, etc.
See MSDN: http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions.updatetargetid.aspx
The relevant code example to give you an idea (unfortunately, it's not in the more readable Razor syntax):
The relevant line is the Ajax.BeginForm where the form tag is rendered. Once the form is posted, the MS AJAX library will auto update the element specified in "UpdateTargetId" specified in the form's AjaxOptions. In this case, the response will be placed into the SPAN element "textEntered" upon reply from the server. Here, you could progressively render more content to the user to fill out, perhaps another form, etc.
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<p>
Page Rendered: <%= DateTime.Now.ToLongTimeString() %>
</p>
<span id="status">No Status</span>
<br />
<%= Ajax.ActionLink("Update Status", "GetStatus", new AjaxOptions{UpdateTargetId="status" }) %>
<br /><br />
<% using(Ajax.BeginForm("UpdateForm", new AjaxOptions{UpdateTargetId="textEntered"})) { %>
<%= Html.TextBox("textBox1","Enter text")%>
<input type="submit" value="Submit"/><br />
<span id="textEntered">Nothing Entered</span>
<% } %>
I often see, touted as one of the big benefits of ASP.NET MVC, the fact that it gets you closer to the actual page markup, as opposed to the pseudomarkup of WebForms.
If that's the case, then why does the HtmlHelper exist? It seems like all this LabelFor, TextBoxFor stuff is just as much pseudomarkup as <asp:Label> and <asp:TextBox> are in WebForms.
What am I missing? Why is there an HtmlHelper class? Do people use it in real life?
Whilst you are right in saying that HtmlHelper functions do abstract away the exact markup rendered, the big advantage of this is that the views are more DRY and you are able to pass in the necessary parameters to the functions in order to customise the HTML generated.
Rather than having to manually type out a full <input /> tag, complete with value=<%= Model.Property %>, Html.TextBoxFor is a more concise way of outputting the same thing. And as with all DRY approaches, if you need to change the HTML for all textboxes in your application (e.g. to output a new attribute) all you need to do is change the HtmlHelper method.
They seem to me a little like simple, lightweight partial views that are just designed to output some consistent HTML given some input.
The point of HTML helpers is to eliminate tedious and repetitive <input> tags.
Unlike server-side controls, HTML helpers emit raw, (fairly-)predictable HTML.
It simplifies the creation of those and allows them to be strongly named. Of course people use this!
I don't quite agree with the answers, and i somehow agree with you.
You can think of the helpers as pre-built custom controls, if you want to have some code generated you can make use of the helpers, if you want a clean approach and get closer to the html then don't.
The important point here is that MVC allows you to get close to the html, but does not limit you to only that.
You can create your own helper that created the markup you wish, and use that instead.
At the end of the day, it comes down to your own preference, and you can choose to or choose not to be closer to the html