1)如何在id
中以AddBookInCategory
格式传递@Html.EditorFor(model=>model.CategoryID)
。
2)第二,如果在public ActionResult AddBookInCategory(Books book)
中添加新项目后返回到id
的类别,则必须类似于return RedirectToAction("ShowBooksFromCategory", 1);
,但它不起作用。
HomeController中:
public class HomeController : Controller
{
//
// GET: /Home/
TEntities TE = new TEntities();
public ActionResult Index()
{
return View();
}
public ActionResult ShowCategories()
{
return View(TE.Category.ToList());
}
public ActionResult ShowBooksFromCategory(int id)
{
return View(TE.Books.Where(key => key.CategoryID == id).ToList());
}
public ActionResult AddBookInCategory(int id)
{
return View();
}
[HttpPost]
public ActionResult AddBookInCategory(Books book)
{
TE.Books.Add(book);
TE.SaveChanges();
return View();
//return RedirectToAction("ShowBooksFromCategory", 1);
}
}
AddBookInCategory.cshtml:
@model TestDataBase.Models.Books
@{
ViewBag.Title = "AddBookInCategory";
}
<h2>AddBookInCategory</h2>
@using(@Html.BeginForm())
{
<p>Book Name:</p>
<br />
@Html.EditorFor(model=>model.BookName)
<p>Category:</p>
<br />
@Html.EditorFor(model=>model.CategoryID)
<input type="submit" value="Create"/>
}
Index.cshtml
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.ActionLink("ShowCategories", "ShowCategories")
ShowBooksFromCategory.cshtml
@model IEnumerable<TestDataBase.Models.Books>
@{
ViewBag.Title = "ShowBooksFromCategory";
}
<h2>ShowBooksFromCategory</h2>
<table>
@foreach(var item in Model)
{
<tr>
<td>
@item.BookName
</td>
</tr>
}
</table>
@Html.ActionLink("Add item", "AddBookInCategory", new {id=Model.Select(key=>key.CategoryID).FirstOrDefault() })
ShowCategories.cshtml
@model IEnumerable<TestDataBase.Models.Category>
@{
ViewBag.Title = "ShowCategories";
}
<h2>ShowCategories</h2>
<table>
@foreach(var item in Model )
{
<tr>
<td>
@item.CategoryName
</td>
<td>
@Html.ActionLink("ShowBooksFromCategory", "ShowBooksFromCategory", new { id=item.CategoryID})
</td>
</tr>
}
</table>
型号:
public partial class Books
{
public int CategoryID { get; set; }
public string BookName { get; set; }
public int BookID { get; set; }
}
public partial class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
}
答案 0 :(得分:1)
嗨@ A191919要使用int重定向,您可以执行以下操作(这与您在actionlink中为获取第一个表单完全相同...)
return RedirectToAction("ShowBooksFromCategory", new { id = book.CategoryID });
要将ID添加到表单中,您可以使用ViewBag。
public ActionResult AddBookInCategory(int id)
{
ViewBag.id = id;
return View();
}
使用viewbag值填写表单输入。