我有一个问题(某种"双面"因为在第一个示例代码中工作,在第二个 - 不是)。当我为Category,field" RootCategory"使用Create函数时使用RootCategoryId按类别对象自动填充(如果需要,则为null)。 这项工作正是我想要的以及它必须如何!
BUT!
在后一种情况下,使用Service and Create for it,object" Category" 始终为空!我认为,它必须工作相同,但事实并非如此!
哪里出错? 帮助我!有一些关于FK的想法(在类别FK =>类别PK中),(在服务FK =>类别PK中),但看起来代码必须没有差异。
我有两个实体模型(代码优先):
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public int? RootCategoryId { get; set; }
public virtual Category RootCategory { get; set; }
}
并且
public class Service
{
public int Id { get; set; }
public string Name { get; set; }
public int Cost { get; set; }
public string Comment { get; set; }
public int? CategoryId { get; set; }
public virtual Category Category { get; set; }
}
背景是:
public class SiteContext : DbContext
{
...
public DbSet<Service> Services { get; set; }
public DbSet<Category> Categories { get; set; }
...
}
让我们看看创建功能。 对于类别:
public ActionResult Create()
{
SelectList ct = new SelectList(db.Categories, "Id", "Name");
ViewBag.Cats = ct;
return PartialView("Create");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Category category)
{
db.Categories.Add(category);
db.SaveChanges();
return RedirectToAction("Index", "Admin");
}
服务:
public ActionResult Create()
{
SelectList ct = new SelectList(db.Categories, "Id", "Name");
ViewBag.Categ = ct;
return PartialView("Create");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Service service)
{
db.Services.Add(service);
db.SaveChanges();
return RedirectToAction("Index", "Admin");
}
和偏见:
@model DialService.Models.Category
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Id)
<div>
@Html.LabelFor(model => model.Name)
<p>@Html.EditorFor(model => model.Name)</p>
</div>
<div>
@Html.LabelFor(model => model.RootCategoryId)
<p>@Html.DropDownListFor(model => model.RootCategoryId, ViewBag.Cats as IEnumerable<SelectListItem>, string.Empty)</p>
</div>
<p><input type="submit" value="Добавить" /></p>
}
和
@model DialService.Models.Service
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Id)
<div>
@Html.LabelFor(model => model.Name)
<p>@Html.EditorFor(model => model.Name)</p>
</div>
<div>
@Html.LabelFor(model => model.Cost)
<p>@Html.EditorFor(model => model.Cost)</p>
</div>
<div>
@Html.LabelFor(model => model.Comment)
<p>@Html.EditorFor(model => model.Comment)</p>
</div>
<div>
@Html.LabelFor(model => model.CategoryId)
<p>@Html.DropDownListFor(model => model.CategoryId, ViewBag.Categ as IEnumerable<SelectListItem>)</p>
</div>
<p><input type="submit" value="Добавить" /></p>
}