ASP.NET MVC 2 Point Return Links to Appropriate View - model-view-controller

The default scaffolded views generated by ASP.NET MVC 2 contain links such as:
<%: Html.ActionLink("Back to List", "Index") %>
<%: Html.ActionLink("Create New", "Create") %>
These links are perfect if I came to this page from that same root. But for example, if I have Orders and Persons and I navigate to /Orders/Edit/17 via /Persons/Orders/3, then 'back to list' returns me to Orders root not Persons root, where I want to go, because the 'Edit Orders' view only knows about orders. This makes the navigation awkward and breaks the flow..
I want to reuse the same 'Edit Orders' view regardless of where I came from, but I'm not sure how to pass this information.
I know it's possible to pass parameters like /Orders/Edit/17?myparam=myvalue but will this limit my choices later on if I need to pass parameters which indicate Sort/Filter order for grids?
What is the preferred way to pass a return/origin location to my view so that it can render the links properly? Otherwise, how can I call the view differently from the controller?
EDIT:
For a clean solution, see THIS POST

Passing in parameters through the querystring will not really limit you as long as you don't use the same names. There is a size restriction on querystrings, but you'll probably not hit it.
That's basically how I do it. I'm curious to see what others answer.

This functionality seems like something that should have been accounted for in the framework; it seems fairly hacky to have to specify these parameters because you'd have to do so for every level of navigation.
Why? back is something that belongs in browsers, along with history. Its been like that for a while, why should the framework need to handle that?
What you need its not the norm.
Additionally, you are responsible to keep your code dry. You can definitely handle it in a way that all the repetition you have is the name of the function you are calling.

Related

a rails partial but used by multiple views

I have a piece of code that I would like to have show up on several areas... from two different views. Which is to say handled by two different controllers (all the data comes from a helper though) what is the best way to break this up, should these partials be rendered then as lay outs? Though they use the twitter bootstrap modal and I have had huge issues getting those to show correctly when called from a layout (most the reason why I have to break up this code into a partial, one that comes from one index.erb.html and another that comes from a partial of its own _document_header.erb.html good time to ask, can you stuff one partial within another...
so just trying to get some pointers. This code is really common to two views.
(and is not always needing to be rendered or displayed)...so want to do this the best way.
You can reference a partial that is anywhere in your views folder.
It's common to make a "shared" folder in your views and reference the partial like: <%= render 'shared/my_partial' %>

How can I take better advantage of Entity Model validation?

I currently have:
#Html.EditorFor(model => model.PurchasePrice)
I would like to split this into 2 separate fields separated by a decimal (for price input obviously). But if I do that using basic text boxes I will loose the ability to take advantage of ASP.NET's validation.
Is there a way to do this, in Razor or by using attributes, so that I am able to keep the JS and server-side validation against my Entity model?
I can easily do it somewhere else by creating my own functions within the viewmodel, but I'm new to MVC3 and not entirely sure if that would be the best route or there is a simpler method.
Edit:
This is kind of the direction I am thinking, I do not fully understand how this works.
I set 2 fields, 1 as ppDollar and 1 as ppCents. In the controller I have:
modelname.PurchasePrice = Request["ppDollar"] + Request["ppCent"];
But, I can look at that and tell that's not going to work. So, I guess the question really is how is user input validated against the entity model and how can I better take advantage of the built in functionality?
You can create custom editors for particular types that are rendered by EditorFor. You can find a lot of examples of how to do this online, most of them focusing on a custom DateTime editor but the same idea applies to any type. Just one example from a quick search:
http://buildstarted.com/2010/09/10/overriding-displayfor-and-editorfor-to-create-custom-outputs-for-mvc/
In short, the process is:
Create a partial view template, placed in the Views\Shared\EditorTemplates folder, with the same name as the type (e.g. Decimal.cshtml).
The view should use, as its model, the type you want to display: #inherits System.Web.Mvc.WebViewPage<System.Decimal>
Make the view display whatever you want, using some field naming convention or whatever.
You can also pass HTML attributes via the appropriate EditorFor overload, referenced in your template through the ViewData.ModelMetadata.AdditionalValues property.
One thing to note: once you define an editor template it will be used for every call to EditorFor. You can scope them to a specific controller by moving the EditorTemplates folder into the appropriate view subfolder instead of the shared one.

Partial View or HtmlHelper for displaying list of items

I have a model that contains an IEnumerable of a list of custom objects. Each item needs to be displayed with about 6 fields and an image. So, I won't be using a grid to display the items, rather a div and styling to achieve the look I want. With that said, I'm looking for the appropriate approach. In the book I have, Pro ASP.NET MVC 3 Framework by Adam Freeman and Steven Sanderson, they give an example of doing something similar in their Sports Store application, where for each item, they use this code,
#foreach(var p in Model.Products) {
Html.RenderPartial("ProductSummary", p);
}
Most other reading that I've done, and what seems to be a preferred approach to this, would be to use an HtmlHelper that does basically the same thing.
Which is preferred and why would I use one approach over the other?
Thanks
EDIT
I should have mentions that each of my items will be enclosed in it's own form and have a submit button. This may be the reason the authors of the book I mentioned used the partial view.
In my opinion, I would go the helper route if there is a chance that the code would be reused somewhere else. Could it be used on another page? Or in another project?
Something else to think about...
Helpers also help you to encapsulate view code so that you can keep your view clean and simple. How complex is that view? Would encapsulating some of the code assist in making the code easier to read and maintain?

Inplace Editing vs. Edit Page

When you develop web applications, especially ones that deal with a good amount of data management (e.g. contacts, addresses, orders and so forth), do you usually create the interface as in-place edit or make a separate "edit" page (and a view-only page)?
Why / What is the advantage of one over the other? I'm trying to make a decision on my own project which has such data management and I'm not sure which way to go.
I think inline editing makes sense when the 'cost-of-effort' of making the change is relatively low.
For example, changing a description on a photo is something that's pretty easy to do, there's little risk if its not exactly right, and the user expects to do it right in context with the picture they're editing. In that case, inline makes sense to me.
On the other hand, in an application where the user needs to be helped or guided through a process, or the change means major changes in billing/shipping/account status. It may make sense to have a separate page to help them understand the full ramifications of their actions.
for things like settings where the main use for viewing the page is to edit it, inline makes sense.
After that, it's more about the usage. If people are constantly editing them then it should just be inline. If it's for say user details, where it is mostly read and sometimes changed, this is what I do:
The page is viewed without editable boxes.
If the user wishes to change some information, they hit an edit button
The same page is shown but with editable fields and cancel / submit buttons.
I achieve this by having the view decide based on a value in the property bucket which version of each field to show, which is set by the action (MVC)
EDIT:
Sample as requested (untested)
In the controller (castle monorail), let's say CustomerController:
public void View(int customerid)
{
PropertyBag["customer"] = Customer.Find(customerid);
}
public void Edit(int customerid)
{
PropertyBag["editing"] = true;
View(customerid);
RenderView("View");
}
in the View (brail):
<th>Name:</th>
<td>
<% if IsDefined("editing"): %>
<input name="c.Name" value="$customer.Name" />
<% else: %>
$customer.Name
<% end %>
</td>
I would say that you should use in-place editing when editing the data is straightforward and simple (idiot-proof). It should be no more complicated to the user than selecting text in a word processor and typing over it.
If you need/want to show labels, instructions, error messages etc, you should probably use a dedicated edit page. Or find a clever way to do this in-page.
Also, sometimes you don't show exactly what the user entered. For example, you show the user's age, but when editing it shows the birthdate. Then I would suggest that you use an edit page, since it could be confusing to the user.

Reload the page without submitting it back to the server

the problem I have is that I have two sets of values in a drop down list. If type 'A' is selected I want a text box to be populated with a value from the database and be read only. If Type 'B' is selected the box is to be empty and editable.
My original code is written in jsp/struts and I have sort of achieved this by using
onchange="javascript:submit()" to reload the page, but this has the obvious drawback of saving any changes you have made which means you can't really cancel.
I also have other problems with the serverside validation due to this method.
Is there a way of making a jsp page reload on change, that way I could write javascript to change the way the page looks according to the values held in the session. That way the save/submit function will only be called when the page has properly been filled out and the server side validation will work as designed.
I know that this is something that AJAX is good at doing but I am trying to avoid it if possible.
AJAX is your only other option my friend, unless on the original page load you load all the other possible values of the Text Box so you don't need to go back to the database. Well, you could try putting the text box in an IFRAME, but you will probably run into more problems with that approach than just going with AJAX.
Without AJAX what you are asking is going to be difficult. Another option (which is ugly) is to write out all possible values for the second list box into a data structure like an array or dictionary.
Then write some javascript to get the values from the data structure when the user selects from the first list box. The amount of javascript you will have to write to get this done and to do it correctly in a cross browser way will be much more difficult than simply using AJAX.
Not sure why you'd try to avoid AJAX in today's world, the JS libraries out there today make it so simple it's crazy not to try it out.
I just had to replace a page that was written as Vincent pointed out. I assume at the time it made sense for the app, given the relative size of the data 4 years ago. Now that the app has scaled though, the page was taking upwards of 30 seconds to parse the data structures repeatedly (poorly written JS? maybe).
I replaced all the logic with a very simple AJAX call to a servlet that simply returns a JSON response of values for the 2nd drop down based on what was passed to it and the response is basically instant.
Good luck to ya.
One way is to change the form's action so that you submit the form to a different url than the "save" url. This lets you reload certain aspects of the form and return to the form itself, instead of committing the data.
<script>
function reload() {
document.forms[0].action="reloadFormData.jsp";
document.forms[0].submit();
}
</script>
<form action="saveData.jsp" method="post">
<select id="A" name="B" onchange="reload()"><!-- blah --></select>
<select id="B" name="B"><!-- blah B --></select>
<input type="submit">
</form>
If I understand you correctly, that you want either a dropdown (<select>) or a textfield (<input type="text">) depending on a choice (typically a checkbox or radiobuttons) somewhere above in a form?
I that case you may need to handle the two types of input differently on the server anyway, so why not have both the selectbox and textfield in the area of the form with different names and id and one of them hidden (display = none). Then toggle visibility when the choice changes. On the server you pick eiter the selectbox or textarea input (wich will both be present unless you disable (disabled="disabled") them too, wich I think is uneccesary) depending on the choice input.
Of course if you expect that the user usually just need the text-input, and a few times only, needing a massive list; it would be better to use ajax to retrieve the list. But if it's the other way around (you need the text-field only occationally), as I assumed above, it will be faster to have both present in the initial form.
If the drop down only contain easily generateable data, like years from now to houndreds of years back it could even be much faster (requiring less bandwidth on the server) to generate the data client side using a for loop in Javascript.
I know a taglib that can fit to your problem:
AjaxTags.
I use this taglib in my J2EE projects and it is very simple to integrate it into web applications.
This taglib give you several tags designed to execute AJAX request in your jsp files.
Here is the description of each tags: http://ajaxtags.sourceforge.net/usage.html
The tag which will help you is the ajax:select tag. It allows you to populate a select tag which depends on an other field without reloading the entire jsp page.
If you more informations about it, ask me and i'll try to answer quicky.
Along the lines of what Strindhaug said, but if you need dynamic data:
Could you have the backend write JS into the page, and then the JS would change the form as required? The backend could propagate some variables for descriptions and such, and then the JS could change/update the form accordingly. If you aren't familiar with this, libs like jQuery make things like this easier and more cross-browser than rolling-your-own (at least in my experience).
Aside:
If you're not using AJAX because it was hard to code (as I didn't for a while because my first experience was from scratch and wasn't pretty), as others have said, libs like MooTools and such make it really easy now. Also, there is not shame in using AJAX properly. It has a bad rap because people do stupid things with it, but if you can't simply write premade values into the form or you have to do live look ups, this is one of AJAX's proper uses.

Resources