473,756 Members | 3,390 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ASP.NET MVC: Multiple Models in a View

Frinavale
9,735 Recognized Expert Moderator Expert
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 PersonControlle r, 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 PersonSearchMod el 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 PersonSearchMod el.SearchCriter ia 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 9242
Frinavale
9,735 Recognized Expert Moderator Expert
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 PersonSearchMod el.SearchCriter ia, the second parameter was the FormCollection for the view.

I am able to create the PersonModel used for the PersonSearchMod el.SearchCriter ia 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 Recognized Expert Moderator Expert
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 SearchPersonsMo del 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.Se archCriteria.Fi rstName" and "searchModel.Se archCriteria.La stName".

"searchMode l" 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 SearchPersonsMo del that is passed it as the "searchMode l" 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 New Member
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 Recognized Expert Moderator Expert
I think the best place to start would be Microsoft's ASP.NET MVC website.

-Frinny
Dec 11 '09 #5
sanjib65
102 New Member
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
8792
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, examples where something like a simulation model running in its own thread sends fast updates to a GUI in near real-time. The only examples I've seen, such as SimPy, wait until the model is finished running before outputting data.
1
6454
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 MVC-ipmlementation from the JAVA by using the observer-pattern. I used an interface IObservable (AddObserver, RemoveObserver,...). My Model implemented this interface.
5
9492
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 in a Windows Forms app I created from scratch. Pretty cool how the form is sitting there and gets populated from the Presenter - and the Form is pretty dumb (i.e., it really has no clue where it's getting populated from.). I understand that...
0
3085
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 Swing model classes. Is it better to use only Swing or only Observer/Observable? In my view class (JFrame) I have a JListbox and if I select one entry, the view class calls a method of the data model and the model class notifies its observer (and...
5
1378
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 very easily Now my problem is very specific. We have a main screen which shows some data called Main view. We have a controller calss which holds a reference to the object of Main view and
4
1605
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 trouble understanding how views work. I have understood (from web reading) that MVC is a flexible approach and not something strict so I want some advice.
2
1243
by: jack | last post by:
Hi guys, I wanted to know whats the difference between MVC and MVP pattern. Thanks
4
3769
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
1321
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 used for gui, and the gui part of the application shouldn't acces directly to your model logic. This why there is a third layer which abstract the logic of your datas and provide standard operation for the gui code. This third layer...
0
10031
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9869
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9838
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9708
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8709
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6534
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5302
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3805
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2665
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.