1) How to pass id in AddBookInCategory form in @Html.EditorFor(model=>model.CategoryID).
2) And second how after adding new item in public ActionResult AddBookInCategory(Books book) return to category with id it must be something like return RedirectToAction("ShowBooksFromCategory", 1); but it does not work.
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>
Models:
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; }
}