【发布时间】:2020-11-22 00:44:37
【问题描述】:
这是我的第一篇文章,所以请温柔.. 我正在使用 vs 2017,asp.net core 2.2 我在使用存储库模式管理 ViewModel 的数据库中保存对象的方法有问题。 我试图从 VM 使用的表 Offer 中的表 Category 中保存 id。我希望 Offers 视图中的 Category 在 DropDownList 中显示为 NameCategory,并将值 Id 保存到 Offers 表中。这是我的文件:
类:
public class Offers
{
public int Id { get; set; }
public string Title{ get; set; }
public string Contents{ get; set; }
public int CategoryId { get; set; }
public Category Categorys { get; set; }
public string PicturePath { get; set; }
}
public class Category
{
[Key]
public int CategoryId { get; set; }
public string NameCategory { get; set; }
public IEnumerable<Offers> OffersList { get; set; }
}
视图模型:
public class OffeersVM
{
public string Title { get; set; }
public string Content { get; set; }
public Category Category{get;set;}
public List<IFormFile> Picture { get; set; }
}
控制器:
[HttpPost]
public IActionResult Create(OffeersVM model)
{
if (ModelState.IsValid)
{
string uniqueName = ProcesEditPicture(model);
Offers newOffers = new Offers
{
Title= model.Title,
Content = model.Content,
CategoryId = model.Category,//I think this is not corect...
PicturePath = uniqueName
};
_offer.Add(newOffers);
return RedirectToAction("details", new { id = newOffers.Id });
}
return View();
}
查看:
@model OffeersVM
@{
ViewBag.Title = "Add offer.";
}
<form asp-controller="Home" asp-action="Create" method="post" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="Title">Title</label>
<input asp-for="Title" class="form-control" id="exampleFormControlInput1" placeholder="Title">
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Select category.</label>
<select class="form-control" id="exampleFormControlSelect1" asp-for="Category" asp-items="@*I't know what item...?*@">
<option value=" test">Please select category.</option>
</select>
<span asp-validation-for="Category"></span>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1" asp-for="Content">Content offer.</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="6" asp-for="Content"></textarea>
<span asp-validation-for="Content" class="text-danger"></span>
</div>
<div class="form-group">
<div class="col-sm-10">
<div class="custom-file">
<input multiple asp-for="Picture" class="form-control custom-file-input " />
<label class="custom-file-label ">Picture</label>
</div>
</div>
</div>
<div>
<button type="submit" class="btn btn-outline-success">Add offer</button>
</div>
</form>
我不知道如何使用 SelectList 或 List 来提供 Id Category。如果任何人都知道一些关于 repository pater 的好教程,或者(更好)可以帮助解决我的问题,我将不胜感激。 亚当。
附言 对不起我的英语...
【问题讨论】:
-
嗨@AaddaammJJ,关于这个案例有什么更新吗?
标签: entity-framework asp.net-core-mvc viewmodel repository-pattern