문제

I'm setting up a simple web with Razor controllers to use as an in-house GUI for interfacing with parts of our database. For the most part this goes smoothly, however when it comes to foreign keys, apparently the first column of the referenced table (when sorted alphabetically) becomes the default representation (i.e. what's shown in the drop down box when editing).

As an example, I have a Campaigns table which has a foreign key to Companies. There is a Companies.Name column which I'd like to be used when displaying Campaigns.CompanyId. However, Razor apparently autopicks the first available, using Companies.AccessKey (which is pretty unintelligible) to represent the company.

I'm looking for some way to specify which columns are used for representing a row, hopefully without altering the auto generated files.

This is driving me nuts, and although I would assume it's a common issue, for some reason my googling doesn't drum up any answers :(

도움이 되었습니까?

해결책

I do not know of a way to set this from the model side, but it can be solved in the view.
Replace the

@Html.DropDownList("Fk_Company", String.Empty)

with

@Html.EditorFor(m => m.Company, "Company") // adapt namings to fit your needs

and add a partial view called Company to /Views/Shared/EditorTemplates containing something like:

@model Company

@Html.DropDownFor(m => m.Name, m.GetValues())

This gives a very simple overview of how you can define custom editor templates (works the same for display templates).
If you name the template exactly like the type it is even picked up automatically and you may not even need to alter the generated view (I am not shure it works automagically with the DropDownList("Fk_Company", String.Empty) syntax, but it does for the EditorFor).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top