【发布时间】:2016-03-18 12:22:28
【问题描述】:
有很多问题反过来询问这个逻辑,但是,我找不到我的问题的答案。我是 MVC 新手,所以可能没有正确指定术语。
我有一个包含表单的视图,用户可以在其中请求产品。无论产品如何,都使用相同的视图,但特定字段显示在与该特定产品相关的表单中,例如
public class RequestController : Controller
{
// This bit works fine and displays the appropriate form in the view
public ActionResult MyProduct(string id)
{
if (string.IsNullOrWhiteSpace(id))
{
return new HttpNotFoundResult();
}
ProductRequest qd = new ProductRequest();
switch (id)
{
case "Beer":
qd.RequestType = Models.RequestType.Beer;
break;
case "Coffee":
qd.RequestType = Models.RequestType.Coffee;
break;
case "Soda":
qd.RequestType = Models.RequestType.Soda;
break;
}
return View("Index", qd);
}
// Need to get all forms rendered by the above to post here...
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MyProduct(ProductRequest qd)
{
if (!ModelState.IsValid)
{
return View(qd);
}
else
{
// To do ...
}
}
}
当表单在视图中呈现时,使用...
@using (Html.BeginForm())
...呈现的 HTML 为每种产品类型显示不同的表单目标 URL,例如:
<form action="/Request/MyProduct/Beer" method="post">
无论产品类型如何,我都可以让form action 属性使用相同的控制器/方法吗?例如
<form action="/Request/MyProduct" method="post">
鉴于 MVC 似乎提供的灵活性,我认为有不同的方法可以实现这一点,但我正在寻找最佳实践作为学习经验。
【问题讨论】:
标签: c# .net asp.net-mvc asp.net-mvc-5