How to page while maintaining the querystring values in ASP.Net Mvc 2 - asp.net-mvc-2

I am using the pager provided by Martijn Boland to implementing paging in my Asp.Net Mvc 2 application.
My form uses the GET method to send all parameters to the querystring, it is a search form with several form elements.
<% using (Html.BeginForm("SearchResults", "Search", FormMethod.Get))
{%>
On the SearchResults View I am trying to implement paging:
<div class="pager">
<%= Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount,
new { Request.QueryString })%>
</div>
The Html.Pager has some overloads which I am not too clear on how to use. The Request.QueryString makes the querystring look like this:
http://localhost:1155/Search/SearchResults?QueryString=Distance%3D10%26txtZip%3D%26cb&page=2
Should it not be like this?
http://localhost:1155/Search/SearchResults?Distance=20&txtZip=10021&page=2

my guess would be to write your pager like this
<%= Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount, new { Distance = Request["Distance"], txtZip = Request["txtZip"] })%>
but it's only a guess, i've never used that...
Edit: see ASP.Net MVC Keeping action parameters between postbacks
so you have to create a RouteValueDictionary from the QueryString which is a NameValueCollection.

Related

How exactly does Rails prefills forms?

I have a (simple) question for my own curiosity:
I'd like to find out how Rails prefill forms with posted values like... you know, when there's a validation error on some models' attributes then you do something like "render :edit" and the form is magically prefilled.
What exactly are the mechanisms that Rails use to do such a thing? I didn't manage to find any documentation on this subject and I'd like to understand the magic.
So if someone can give me some explanations on this subject, I'll be glad to read that!
Thanks!
[Edit] And a subsidiary question: when a model inherits from another (STI) do we have to do something in particular to prefill forms?
You are mostly using the form_for helper in this style:
<%= form_for #person do |f| %>
<!-- Some more stuff here -->
<%= f.text_field :first_name %><br />
<!-- Some more stuff here -->
<% end %>
What this essentiall does is, it generates a text field that is filled with the value of #person.first_name.to_s. When an error happens, #person.first_name is filled with the errornous value. If you create a person (#person = Person.new), then #person.first_name.to_s is "".
So rails just fills the text field with the value, the attribute has.
f by the way is a rails FormBuilder. It's methods are documented here, if you want to take a closer look at the source.

What is Proper MVC 2 Page Navigation Protocol in this instance

I am making progress in my assignment, but have run into a minor sticking point. While I research it, I thought I would ask the question on this forum so if any one else runs into a similar issue, they can rely on the scholarship we present here.
On to the question...
I am rendering data I receive from an XML string into views in a grid format. I want to be able to navigate to another page by clicking on a link that is in that row. That link will take me to another more detailed view of the data presented. I will use some of the data that is display on the link to query my xml (via LINQ to XML) and get the appropriate rows to render on the next page (view). My question is, how would I do this in MVC? In vanilla asp.net I would just put that information into the querystring or some other simple state-management variable. I am little confused how to get this done using MVC2?
Here is the code of what I currently have
<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.ActionLink("View Detailed Patient Info", "TemplateInfo", "PatientACO", new { PopulationPatientID=item.PopulationPatientID } )%> |
</td>
<td>
<%: item.populationID %>
</td>
<td>
<%: item.PopulationPatientID%>
</td>
<td>
<%: item.populationOwner %>
</td>
<td>
Table Column3
</td>
</tr>
<% } %>
That code is in my view, and I want to send that PopulationPatientID to a controller that will then use it to query my XML. Is there an Overload to HTML.ActionLink() that I can use that will help me out with that at all? Did I mention that the ActionLink that I am trying to navigate to requires a string parameter? Any help or ideas would be fantastic. I'll continue my research, and should I come across an industry standard way of doing it I will post an answer.
Thanks.
You don't mention your routing setup, but if you are still using the defaults...
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
You specified the action (TemplateInfo) and controller (PatientACO), but you changed the name of the id parameter to PopulationPatientID. Remember that the name of the parameter is important in MVC (convention vs. configuration). So change your ActionLink() call to:
<%: Html.ActionLink("View Detailed Patient Info", "TemplateInfo", "PatientACO", new { id=item.PopulationPatientID } )%> |

Asp.net Mvc Display template of String, but now every simple type wants to use it!

I created a Display Template which when passed a string renders a disabled text box
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<String>" %>
<%: Html.TextBoxFor(model => model, new { disabled = "disabled" })%>
Which works great. However, for some reason MVC wants to try and stuff DateTimes and Ints through it as well, which is throwing exceptions
The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'System.String'.
Any ideas?
You don't need to strongly type the template to a String.
you can try something like this :
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
, new { disabled = "disabled" }) %>
And in your view you call it like this
Html.DisplayModelFor(model => mode.name);
For more information see an example of the default built-in editor template for the string in Brad Wilson article in his his series on Templates in ASP.NET MVC.
You should consider going through the complete series. I can't express how helpful this series was for me.

MVC2 Custom HTML Helper and <%: %> Syntax

Is there any way to use a custom html helper with the <%: %> syntax ?
I know that if i'm use the code below, it's ok, but it's seems not so elegant and secure.
<%= Html.MyHelper("Some Data")%>
I mean, use <%= %> is the best practices?
Have your helper return an MvcHtmlString instead of a string. Also, please use <%: as much as possible.
HTML helpers create HTML, which is normally expected to be output raw with <%= %>. If you used <%: %> to HTML-escape the output of an HTML helper, you'll see the HTML source it produced on the page as text (eg literally <input name="foo" value="bar"> on-screen), which is probably not what you want.
It is up to the helper to HTML-escape any text content inside them, for safety. Yes, if you write a custom HTML helper and get it wrong—forgetting to HTML-encode strings your helper is putting in text content or attribute values in the output—you'll have security holes. You need to know what you're doing with escaping to write an HTML helper.
Microsoft, unfortunately, apparently don't, as the very first example in their tutorial completely fails:
return String.Format("<label for='{0}'>{1}</label>", target, text);
Whoops. Hope those ID and text strings didn't come from untrusted data!
[why are web tutorials always so lamentably terrible at escaping issues?]

Better approach to role-based UI changes?

I have an MVC view that changes a few small UI elements based on the user's role. Currently it modifies the output using a few if() statements using a couple boolean values I sent to the view through the viewmodel. However, it doesn't seem like a very good approach, so what I'd like to do is move this all into either an HtmlHelper class or the controller itself. Here's the current code:
<% if ( Model.IsAdmin ) { %> <td> <% } %> <%--Opening tag for admin options--%>
<% if ( Model.IsAdmin ) { %> <%:Html.ActionLink("Delete", "Delete", new { id = Id})%> <% } %> <%--Admin options--%>
<% if ( Model.IsAdmin ) { %> </td> <% } %> <%--Closing tag for admin options--%>
There's a seperate spot where I show/hide the create new link as well
<% if ( Model.IsEditor || Model.IsAdmin ) { %>
<%:Html.ActionLink("Create New", "Create") %>
<% } %>
There might be a couple other of these situations as well.
So any HtmlHelper I would build would potentially need a couple overloads for the different cases, so it would probably need to be pretty flexible. I've just been going around and around in my head on the best approach to this, and it seems like a common problem that someone else would probably have come up with already...
Thanks!
Looks like this solution would fit your needs:
Role-Based Content asp.net mvc
Either use a partial views in your views or create different views for each role and render the view according to the role. you can also check RenderAction.