I am Working on ASP.NET MVC 5, EF 6, Razor Engine, VB Language and Database First Approach with VS 2013.
Now, in my DB; I have two tables as below:
CREATE TABLE [dbo].[Group]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
[Name] VARCHAR(50) NOT NULL
)
and
CREATE TABLE [dbo].[Subscriber]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
[FirstName] [nvarchar](100) NOT NULL,
[MiddleName] [nvarchar](100) NULL,
[LastName] [nvarchar](100) NOT NULL,
[Email] [varchar] (200) NOT NULL UNIQUE,
[GroupId] INT NULL REFERENCES [Group] ON DELETE SET NULL
)
Now, when I autogenerate the Controllers and Views using Scaffolding; I get a <select> control (with all Group
items as <option> inside) in "Create Subscriber" and "Edit Subscriber" views.
But actually, I want the "Create Group" and "Edit Group" views to ask me the Subscribers
I want to add in the particular group. The HTML control for the same can be a list of checkbox or <select multiple="multiple"> with all Subscriber
items as <option>s.
How can I autgenerate/implement that?
Don't rely too heavily on the scaffolding. The whole point is that it gives you a base to work from; it's not the be-all-end-all to your view. You can and should modify the scaffolding to suit your needs, and honestly, more often than not, it's easier just to start from scratch than to try to undo all the unnecessary fluff the scaffolding adds.
That said, especially when choosing multiple related items at once, you need a view model. Trying to use your entity for this is going to run out of steam fast. So create a class like:
Then, in your controller:
The edit post action is the most difficult. In order to not get errors about duplicate keys and such, you need to make sure you don't add duplicate items to the collection. You also need to make sure to remove the relationship between this group and any items the user has unselected. Other than that, it's pretty straight forward.
Finally in your views, you just need a to render the select list:
UPDATE
Adding converted VB code. This may not work 100% out of the box. Anyone with more VB experience may feel free to edit this to correct any issues.
View Model
Controller Code