gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 5 - 多对一关系的脚手架

转载 作者:行者123 更新时间:2023-12-02 16:19:23 26 4
gpt4 key购买 nike

我正在使用 VS 2013 开发 ASP.NET MVC 5、EF 6、Razor 引擎、VB 语言和数据库优先方法。

现在,在我的数据库中;我有两个表如下:

CREATE TABLE [dbo].[Group]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
[Name] VARCHAR(50) NOT NULL
)

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
)

现在,当我使用脚手架自动生成 Controller 和 View 时;我在“创建订阅者”和“编辑订阅者” View 中获得一个 ,其中所有 Subscriber 项目均为

我如何自动生成/实现它?

最佳答案

不要过分依赖脚手架。重点是它为你提供了一个工作基础;这并不是您的观点的全部。您可以而且应该修改脚手架以满足您的需求,老实说,通常情况下,从头开始比尝试消除脚手架添加的所有不必要的内容更容易。

也就是说,特别是在一次选择多个相关项目时,您需要一个 View 模型。尝试使用你的实体来做这件事很快就会失去动力。因此创建一个类,例如:

public class GroupViewModel
{
// `Group` properties you need to edit here

public List<int> SelectedSubscriberIds { get; set; }

public IEnumerable<SelectListItem> SubscriberChoices { get; set; }
}

然后,在您的 Controller 中:

// We'll use this code multiple times so it's factored out into it's own method
private void PopulateSubscriberChoices(GroupViewModel model)
{
model.SubscriberChoices = db.Subscribers.Select(m => new SelectListItem
{
Value = m.Id.ToString(),
Text = m.FirstName + " " + m.LastName
});
}

public ActionResult Create()
{
var model = new GroupViewModel();

PopulateSubscriberChoices(model);
return View(model);
}

[HttpPost]
public ActionResult Create(GroupViewModel model)
{
if (ModelState.IsValid)
{
// Map the posted values onto a new `Group` instance. To set `Subscribers`,
// lookup instances from the database using the list of ids the user chose
var group = new Group
{
Name = model.Name,
Subscribers = db.Subscribers.Where(m => model.SelectedSubscriberIds.Contains(m.Id))
};
db.Groups.Add(group);
db.SaveChanges()

return RedirectToAction("Index");
}

PopulateSubscriberChoices(model);
return View(model);
}

public ActionResult Edit(int id)
{
var group = db.Groups.Find(id);
if (group == null)
{
return new HttpNotFoundResult();
}

// Map `Group` properties to your view model
var model = new GroupViewModel
{
Name = group.Name,
SelectedSubscriberIds = group.Subscribers.Select(m => m.Id).ToList()
};

PopulateSubscriberChoices(model);
return View(model);
}

[HttpPost]
public ActionResult Edit(int id, GroupViewModel model)
{
var group = db.Groups.Find(id);
if (group == null)
{
return new HttpNotFoundResult();
}

if (ModelState.IsValid)
{
group.Name = model.Name;

// Little bit trickier here
// First remove subscribers that are no longer selected
group.Subscribers.Where(m => !model.SelectedSubscriberIds.Contains(m.Id))
.ToList().ForEach(m => group.Subscribers.Remove(m));

// Now add newly selected subscribers
var existingSubscriberIds = group.Subscribers.Select(m => m.Id);
var newSubscriberIds = model.SelectedSubscriberIds.Except(existingSubscriberIds);
db.Subscribers.Where(m => newSubscriberIds.Contains(m.Id))
.ToList().ForEach(m => group.Subscribers.Add(m));

db.Entry(group).State = EntityState.Modified;
db.SaveChanges()

return RedirectToAction("Index");
}

PopulateSubscriberChoices(model);
return View(model);
}

编辑帖子操作是最困难的。为了不出现有关重复键等的错误,您需要确保不向集合中添加重复的项目。您还需要确保删除该组与用户未选择的任何项目之间的关系。除此之外,它非常简单。

最后在您的 View 中,您只需要渲染选择列表:

@model Namespace.To.GroupViewModel

...

@Html.ListBoxFor(m => m.SelectedSubscriberIds, Model.SubscriberChoices)

更新

添加转换后的 VB 代码。这可能无法 100% 开箱即用。具有更多 VB 经验的任何人都可以随意编辑此内容以纠正任何问题。

查看模型

Public Class GroupViewModel
' Group properties you need to edit here

Public Property SelectedSubscriberIds As List(Of Integer)
Public Property SubscriberChoices As IEnumerable(Of SelectListItem)

End Class

Controller 代码

' We'll use this code multiple times so it's factored out into it's own method
Private Sub PopulateSubscriberChoices(model As GroupViewModel)
model.SubscriberChoices = db.Subscribers.[Select](Function(m) New SelectListItem With { _
.Value = m.Id, _
.Text = m.FirstName & " " & m.LastName _
})
End Sub

Public Function Create() As ActionResult
Dim model as New GroupViewModel
PopulateSubscriberChoices(model)
Return View(model)
End Function

<HttpPost> _
Public Function Create(model As GroupViewModel) As ActionResult
If ModelState.IsValid Then
' Map the posted values onto a new `Group` instance. To set `Subscribers`,
' lookup instances from the database using the list of ids the user chose
Dim group = New Group With { _
.Name = model.Name, _
.Subscribers = db.Subscribers.Where(Function(m) model.SelectedSubscriberIds.Contains(m.Id)) _
}
db.Groups.Add(group)
db.SaveChanges()

Return RedirectToAction("Index")
End If

PopulateSubscriberChoices(model)
Return View(model)
End Function

Public Function Edit(id As Integer) As ActionResult
Dim group = db.Groups.Find(id)
If group Is Nothing Then
Return New HttpNotFoundResult()
End If

' Map `Group` properties to your view model
Dim model = New GroupViewModel With { _
.Name = group.Name, _
.SelectedSubscriberIds = group.Subscribers.[Select](Function(m) m.Id).ToList _
}

PopulateSubscriberChoices(model)
Return View(model)
End Function

<HttpPost> _
Public Function Edit(id As Integer, model As GroupViewModel) As ActionResult
Dim group = db.Groups.Find(id)
If group Is Nothing Then
Return New HttpNotFoundResult()
End If

If ModelState.IsValid Then
group.Name = model.Name

' Little bit trickier here
' First remove subscribers that are no longer selected
group.Subscribers.Where(Function(m) Not model.SelectedSubscriberIds.Contains(m.Id)).ToList().ForEach(Function(m) group.Subscribers.Remove(m))

' Now add newly selected subscribers
Dim existingSubscriberIds = group.Subscribers.[Select](Function(m) m.Id)
Dim newSubscriberIds = model.SelectedSubscriberIds.Except(existingSubscriberIds)
db.Subscribers.Where(Function(m) newSubscriberIds.Contains(m.Id)).ToList().ForEach(Function(m) group.Subscribers.Add(m))

db.Entry(group).State = EntityState.Modified
db.SaveChanges()

Return RedirectToAction("Index")
End If

PopulateSubscriberChoices(model)
Return View(model)
End Function

关于asp.net-mvc - ASP.NET MVC 5 - 多对一关系的脚手架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27381766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com