Asp.net MVC2: I have many dropdownlists in my mvc application. At first, I started by creating a table for each one wi开发者_如何学运维th a unique ID and name and referring to them in the controllers and views. The application got bigger, and it was suggested that I use a lookup table, that contains lookuptype and lookupvalue as compound primary key and fill all the values for the dropdownlists in it. I've looked all over the internet, the only method used for mvc is one table for each dropdownlist! Can someone explain to me how I can implement it, and in detail please becoz I'm totally lost. A link to a tutorial would also be great. I'm using vb.net and linq to sql.
Suppose your tables have columns ID
, Name
and Value
. Now by having only one table that table would most probably look like this:
create table Lookup
(
LookupID int not null identity
primary key,
LookupTypeID int not null
references LookupType(LookupTypeID),
Name nvarchar(50) not null,
Value int not null,
unique(EnumTypeID, Name)
)
go
This table will make sure that within the same type names don't clash.
Anyway. You could of course have a similar application (not data) model class
public class EnumValue
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Value { get; set; }
}
So whenever you get values of a certain type you can always generate an IList<EnumValue>
of them and feed them to a particular drop down.
Since you didn't provide any valuable data this table and class could omit column/property Value
, because depending on the inner workings it may not be needed at all. But you will know this best because you know your application requirements. Instead of this column/property only ID could do the trick.
I actually used a slightly different approach. I created a table that has a composite primary key, LookupName and LookupValue. Then in the datacontext I declared a method that takes the lookupname as a parameter, and then brings a list of lookupvalues whose lookupname match this parameter. In the original table (ex.Contact) I created a field called status, where the selected value will be saved. Then in the controller, I used viewdata to create dropdownlists.
Example: _db represents the datacontext
Viewdata('Status')= new selectlist(_db.Getlookupname('status'),'lookupname','lookupname')
and then in the view
html.dropdownlist('status')
I also named the dropdownlist with the same fieldname 'status' that is found in the target table 'Contact'.
And it worked, without any complexity or errors. Thanks for the help. And I hope this will be helpful to someone else!
Here's a sort of tutorial on how to achieve a generic lookup service.
http://wtfperminute.blogspot.com/2011/02/working-with-reference-data-lookups.html
Similar to what you've done, but perhaps a bit more comprehensive.
精彩评论