我試圖從我的索引頁面訪問多個操作,而不是爲每個操作分別創建視圖。但我沒有多少運氣,而且我幾乎陷入困境。對同一視圖的ASP.net mvc5 multple動作?
我的BeginForm
無法解析操作Create
也無法解析控制器CategoriesController
。
這是我的控制器:
public class CategoriesController : Controller
{
private readonly ApplicationDbContext _db = new ApplicationDbContext();
public async Task<ActionResult> Index()
{
return View(await _db.Categories.ToListAsync());
}
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,Name")] Category category)
{
if (ModelState.IsValid)
{
_db.Categories.Add(category);
await _db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(category);
}
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Category category = await _db.Categories.FindAsync(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
Category category = await _db.Categories.FindAsync(id);
_db.Categories.Remove(category);
await _db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
這是我的看法
@using MultipleActionsSameView.Controllers
@model IEnumerable<MultipleActionsSameView.Models.Category>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
@using (Html.BeginForm("Create", "CategoriesController", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Category</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
生成<表單操作HTML表單=「/分類/創建」 enctype =「multipart/form-data」method =「post」>? –
@PaulZahra陰性。 –
in beginform控制器的名稱必須是沒有後綴的類別控制器 – user3401335