我有两个表类别和产品。
Category:- CategoryId,CategoryName
Product:- ProductId, ProductName, Price, CategoryId(FK)
我想从单个视图添加数据。 我将类别创建为局部视图并将其呈现为“创建页面”。
控制器是: -
public class ProductController : Controller
{
private StoreDbEntities db = new StoreDbEntities();
//
// GET: /Product/
public ActionResult Index()
{
var products = db.products.Include(p => p.Category);
return View(products.ToList());
}
//
// GET: /Product/Details/5
public ActionResult Details(int id = 0)
{
product product = db.products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
//
// GET: /Product/Create
public ActionResult Create()
{
ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName");
return View();
}
public ActionResult CreateCategory()
{
return View();
}
[HttpPost]
public ActionResult CreateCategory(Category category)
{
if(ModelState.IsValid)
{
db.Categories.Add(category);
db.SaveChanges();
return RedirectToAction("Create");
}
return View(category);
}
//
// POST: /Product/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(product product)
{
if (ModelState.IsValid)
{
db.products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName", product.CategoryId);
return View(product);
}
}
和创建视图是: -
@model MvcApplication9.Models.Category
@Html.Partial("_Category",Model);
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Category</legend>
<div class="editor-label">
@Html.LabelFor(model => model.CategoryName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CategoryName)
@Html.ValidationMessageFor(model => model.CategoryName)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
和_Categoy视图是: -
@model MvcApplication9.Models.Category
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Category</legend>
<div class="editor-label">
@Html.LabelFor(model => model.CategoryName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CategoryName)
@Html.ValidationMessageFor(model => model.CategoryName)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
当我运行它时显示错误&#34;一个或多个实体的验证失败。请参阅&#39; EntityValidationErrors&#39;物业详情。&#34;。请帮我解决这个问题。 在此先感谢。