473,386 Members | 1,699 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

ASP.NET MVC: Multiple Models in a View

Frinavale
9,735 Expert Mod 8TB
I'm playing with an ASP.NET MVC application and I've run into a bit of a problem. I am pretty new to ASP.NET MVC and just barely understand the basics to get things to work at this point.

I have a PersonModel, a PersonController, and a bunch of views that let a user add a new person, edit a person and search for people.

I am not using a DataBase in the back end. Everything I'm doing depends on an external DLL that returns "person" structures (that I turn into PersonModels).

In order to search for people, I have to provide a person-structure that acts as search criteria to a method in the external DLL. The method returns a collection of person-structures that match the search criteria. If I want to retrieve all of the people in the system I supply an empty person-structure to the method.

So, I have the "retrieve all people" function working.....but I'd like to provide an advanced search.

My Search View is bound to a class that contains 2 properties:

Expand|Select|Wrap|Line Numbers
  1. Public Class PersonSearchModel
  2.   Private _searchCriteria As PersonModel
  3.   Private _searchResults As List(Of PersonModel)
  4.   Public Property SearchCriteria As PersonModel
  5.     Get
  6.       return _searchCriteria
  7.     End Get
  8.     Set(ByVal value As PersonModel)
  9.       _searchCriteria = value
  10.     End Set
  11.   End Property
  12.   Public Property SearchResults As List(Of PersonModel)
  13.     Get
  14.       return _searchResults 
  15.     End Get
  16.     Set(ByVal value As List(Of PersonModel))
  17.       _searchResults = value
  18.     End Set
  19.   End Property
  20. End Class
Now the Search View binds to this PersonSearchModel and I have 2 sections...a section where the user can provide search criteria and a section that displays the search results.

I am having a problem binding the PersonSearchModel.SearchCriteria to the controls used to display/gather the Person search criteria.

I cannot retrieve the search criteria.

This what I have in my view for the search criteria:
Expand|Select|Wrap|Line Numbers
  1.  <fieldset>
  2.         <legend>Search Criteria</legend>
  3.         <%
  4.             With Model.SearchCriteria
  5.          %>
  6.         <div style="float:left">
  7.         <p>
  8.             <label for="FirstName">
  9.                 FirstName:</label>
  10.             <%=Html.TextBox("FirstName", Html.Encode(.FirstName))%>
  11.             <%= Html.ValidationMessage("FirstName", "*") %>
  12.         </p>
  13.         <p>
  14.             <label for="LastName">
  15.                 LastName:</label>
  16.             <%=Html.TextBox("LastName", Html.Encode(.LastName))%>
  17.             <%= Html.ValidationMessage("LastName", "*") %>
  18.         </p>
  19.          <!-- More controls -->
  20.         </div>
  21.         <%  End With%>
  22.     </fieldset>
  23.      <%=Html.ActionLink("Search", "Search",Model.SearchCriteria)%>
  24. <!-- The Search Results Section-->
  25.  
The PersonModel passed into the Search method is a new/empty PersonModel Object. So all of the people in the system are returned and displayed but that's not what is supposed to happen. The search is supposed to return Persons that match the search criteria. But it's always empty.

What am I doing wrong here?

-Frinny
Nov 27 '09 #1
5 9204
Frinavale
9,735 Expert Mod 8TB
After much testing and debugging I discovered something interesting: I can retrieve the information entered by the user from the FormCollection passed into the Search Function. Originally my search function took 2 parameters. The first parameter was the PersonModel that was supposed bound to the PersonSearchModel.SearchCriteria, the second parameter was the FormCollection for the view.

I am able to create the PersonModel used for the PersonSearchModel.SearchCriteria based on the FormCollection passed into the Search function. I removed the first parameter (the PersonModel) since it was always a new/empty object.

This is my current Search method:
Expand|Select|Wrap|Line Numbers
  1. <AcceptVerbs(HttpVerbs.Post)> _
  2. Function Search(ByVal collection As FormCollection) As ActionResult
  3.         Dim searchModel As New SearchPersonsModel
  4.  
  5.         Dim personProperties() As PropertyInfo = GetType(PersonModel).GetProperties
  6.         For Each pi As PropertyInfo In personProperties
  7.             Dim piName As String = pi.Name
  8.             Dim info As String = Array.Find(collection.AllKeys, Function(x) x.Compare(piName, x, true) = 0)
  9.             If String.IsNullOrEmpty(info) = False Then
  10.                 pi.SetValue(searchModel.SearchCriteria, collection.Item(info), Nothing)
  11.             End If
  12.         Next
  13. 'The following line uses the searchModel.searchCriteria to search for People.
  14. End Function
My View (if your curious) looks like:

Expand|Select|Wrap|Line Numbers
  1.  <% Using Html.BeginForm()%>
  2.  <%With Model.SearchCriteria%>
  3.   <fieldset>
  4.     <legend>Search Criteria</legend>
  5.       <div style="float: left">
  6.         <p>
  7.           <label for="FirstName">FirstName:</label>
  8.           <%=Html.TextBox("FirstName", Html.Encode(Model.SearchCriteria.FirstName))%>
  9.            <%=Html.ValidationMessage("Model.SearchCriteria.FirstName", "*")%>
  10.         </p>
  11.         <p>
  12.             <label for="LastName">LastName:</label>
  13.             <%=Html.TextBox("LastName", Html.Encode(Model.SearchCriteria.LastName))%>
  14.             <%=Html.ValidationMessage("Model.SearchCriteria.LastName", "*")%>
  15.         </p>
  16.       <!---..... more controls .... -->
  17.     </div>
  18.   </fieldset>
  19.   <%End With%>
  20.   <input type="submit" value="Search" />
  21.  
  22. <!-- Search Results Controls -->
  23.  
  24.   <%End Using%>
This solution works but I am really not happy with it.
This seems ridiculous to me!

Why do I have to recreate the PersonModel used as the search criteria?

Why can't I pass the PersonModel (the search criteria) into the Search function?

-Frinny
Dec 7 '09 #2
Frinavale
9,735 Expert Mod 8TB
I doubt anyone's interested in this thread but I'm going to keep updating it regardless.

I finally found a better answer to my problem. I add the first parameter back into the Saerch method. Recall that originally the first parameter was the PersonModel that I was using as the search criteria, now I'm passing a SearchPersonsModel instead.

What I discovered is that I have to use the name of this parameter in the names for the controls that I'm using in the View to display/gather the search criteria.

It's hard to explain so here's an example of what I'm talking about.

Here is my current Search method:
Expand|Select|Wrap|Line Numbers
  1. <AcceptVerbs(HttpVerbs.Post)> _
  2. Function Search(ByVal searchModel As SearchPersonsModel, ByVal collection As FormCollection) As ActionResult      
  3.   '...Code that uses the searchModel.searchCriteria to search for People...
  4.   'Displaying the results
  5.   View(searchModel)
  6. End Function
Here is my Search View:
Expand|Select|Wrap|Line Numbers
  1.  <% Using Html.BeginForm()%>
  2.  <%With Model.SearchCriteria%>
  3.   <fieldset>
  4.     <legend>Search Criteria</legend>
  5.       <div style="float: left">
  6.         <p>
  7.           <label for="FirstName">FirstName:</label>
  8.           <%=Html.TextBox("searchModel.SearchCriteria.FirstName", Html.Encode(Model.SearchCriteria.FirstName))%>
  9.            <%=Html.ValidationMessage("Model.SearchCriteria.FirstName", "*")%>
  10.         </p>
  11.         <p>
  12.             <label for="LastName">LastName:</label>
  13.             <%=Html.TextBox("searchModel.SearchCriteria.LastName", Html.Encode(Model.SearchCriteria.LastName))%>
  14.             <%=Html.ValidationMessage("Model.SearchCriteria.LastName", "*")%>
  15.         </p>
  16.       <!---..... more controls .... -->
  17.     </div>
  18.   </fieldset>
  19.   <%End With%>
  20.   <input type="submit" value="Search" />
  21.  
  22. <!-- Search Results Controls -->
  23.  
  24.   <%End Using%>
Note that the TextBoxes are named "searchModel.SearchCriteria.FirstName" and "searchModel.SearchCriteria.LastName".

"searchModel" is the name of the first parameter in the Search method. These have to match.

Now when the user clicks the "Search" submit button, ASP.NET MVC creates and populates the SearchPersonsModel that is passed it as the "searchModel" parameter in my Search method. It creates and populates the Object using reflection. This all has something to do with Binders.

I am currently researching Binder Objects because even though I'm happy that I don't have to use reflection to populate my model based on the form collection, I'm still not 100% happy with the "magic" that is happening behind the scenes here.

-Frinny
Dec 8 '09 #3
sanjib65
102 100+
I'm following your thread with interest and want to learn MVC. As it is completely new concept in ASP.NET I'll be grateful if you kindly let me know where can I get to know the basics? Thanks in advance :)
Dec 11 '09 #4
Frinavale
9,735 Expert Mod 8TB
I think the best place to start would be Microsoft's ASP.NET MVC website.

-Frinny
Dec 11 '09 #5
sanjib65
102 100+
I checked and bookmarked. Yes, that's the good place to start with MVC. Many thanks.
Dec 11 '09 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: pysim | last post by:
Hi, I have a couple of general requests for pointers to python examples and design advice. I'm looking for examples of MVC-based GUI controls done in python (model-view-controller). Also,...
1
by: Marcel Hug | last post by:
Hi NG ! I have already written a task about MVC and I tried to get the best informations together. I would like to implement the MVC pattern and it work on the way I did it. At first i know the...
5
by: Jeff S | last post by:
Okay, I just finally figured out the Model View Presenter pattern as presented by Martin Fowler (http://www.martinfowler.com/eaaDev/ModelViewPresenter.html). I even got a small model of it working...
0
by: Andre Rothe | last post by:
Hi, Can anyone give me a recipe to handle the following problem: I try to use Observable in the data model class and Observer in the view class. But I'm unsure, how I can combine these with...
5
by: -pb- | last post by:
Hi, We are developing an windows application and decided to use the MVC design pattern. We decided to use windows application due to varuous business processes which cannot be implemented in web...
4
by: Harris Kosmidhs | last post by:
Hello, I 'm writting an application using an MVC approach of mine (not with a framework). Notice that I 'm not writting a framework but an application with such an approach. I 'm having...
2
by: jack | last post by:
Hi guys, I wanted to know whats the difference between MVC and MVP pattern. Thanks
4
by: Aaron Gray | last post by:
I am after opend source small, middle or large example programs thay use MVC pattern coded Javascript. Many thanks in advance, Aaron
0
by: Maric Michaud | last post by:
Le Tuesday 16 September 2008 14:47:02 Marco Bizzarri, vous avez écrit : It is not about QT, it is about MVC. In MVC, code which implement the model should be completely ignorant of the libraries...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.