gpt4 book ai didi

asp.net-mvc-4 - 通过将ViewModel发送到 Controller 来更新存储库模式模型-如何发送回上下文?

转载 作者:行者123 更新时间:2023-12-03 10:28:59 24 4
gpt4 key购买 nike

我有一个管理员部分,其中包含/Admin/NewCourse 页面,我想使用该页面通过表单保存新添加的类(class)详细信息。首先使用存储库模式使用POCO创建类(class)模型。

我认为我有以下几点:

@using(Html.BeginForm("NewCourse","Admin",FormMethod.Post))
{
<div class="row">
<div class="twelve columns">
<div class="row">
<div class="six columns">
@Html.LabelFor(c => c.Course.Name)
@Html.TextBoxFor(c => c.Course.Name)
</div>
<div class="six columns">
@Html.LabelFor(c => c.Course.Author)
@Html.TextBoxFor(c => c.Course.Author)
</div>

<div class="row">
<div class="six columns">
@Html.LabelFor(c => c.Course.UploadDate)
@Html.TextBoxFor(c => c.Course.UploadDate)
</div>
<div class="six columns">
@Html.LabelFor(c => c.Course.ExpiryDate)
@Html.TextBoxFor(c => c.Course.ExpiryDate)
</div>
</div>

<div class="row">
<div class="twelve columns">
@Html.LabelFor(c => c.Course.Description)
@Html.TextAreaFor(c => c.Course.Description)
</div>
</div>

<div class="row">
<div class="six columns">
@Html.LabelFor(c => c.Course.ParticipationPoints)
@Html.TextBoxFor(c => c.Course.ParticipationPoints)
</div>
</div>
</div>
</div>
<input type="submit" value="Submit button"/>
</div>

}

在我的 Controller 中,我以以下方式设置了HTTP发布:
[HttpPost]
public ActionResult NewCourse(AdminViewModel model)
{
Course newCourse = new Course();
newCourse.Name = model.Course.Name;
newCourse.Author = model.Course.Author;
newCourse.UploadDate = model.Course.UploadDate;
newCourse.ExpiryDate = model.Course.ExpiryDate;
newCourse.Description = model.Course.Description;
newCourse.ParticipationPoints = model.Course.ParticipationPoints;
return View(model);
}

从上面的POST中可以看到,我正在传递一个AdminViewModel,其中包含以下代码行:
 private Repository<Course> courseRepository;   

如何在 Controller 中更新我的POST方法,以将新类(class)的更改保存到courseRepository列表中?

最佳答案

这取决于存储库的实现以及是否实现了save方法。

在执行存储库模式时,我是通过t4脚手架完成的。它具有以下两种方法来处理插入或更新。

public void InsertOrUpdate(TEntity entity)
{
dynamic ent = entity;

if (ent.Id == default(System.Guid)) {
// New entity
ent.Id = Guid.NewGuid();
_context.Set<TEntity>().Add(ent);
} else {
// Existing entity
_context.Entry(ent).State = EntityState.Modified;
}
}

public void Save()
{
_context.SaveChanges();
}

因此,我首先通过传递新创建的实体来调用insert或update方法。
然后调用save方法,该方法将保存该上下文中的更改。

希望能有所帮助。

干杯,
阿米拉

关于asp.net-mvc-4 - 通过将ViewModel发送到 Controller 来更新存储库模式模型-如何发送回上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17422460/

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