HTTPPOST 属性在 MVC 中不起作用
HTTPPOST Attribute not working in MVC
我有一个控制器,其中定义了两个动作。
public class ExamlpeController : Controller
{
[Route("Index")]
public ActionResult Index()
{
return View(new ExampleViewModel { Message = new MessageDisplay { MessageVisible = false, IsGoodMessage = true, Message = String.Empty } });
}
// POST:
[HttpPost]
[Route("Index/{exampleData?}")]
public ActionResult Index(ExampleViewModel exampleData)
{
if (!ModelState.IsValid) // If model state is invalid
// Return view with validation summary
return View(new ExampleViewModel { Message = new MessageDisplay { MessageVisible = false, IsGoodMessage = true, Message = String.Empty } });
else // If model state is valid
{
// Process further
bool isGoodMessage = true; // Default
string message = "success";
isGoodMessage = true;
message = "test data";
// Clear model state if operation successfully completed
if (isGoodMessage)
ModelState.Clear();
return View(new ExampleViewModel { Message = new MessageDisplay { IsGoodMessage = isGoodMessage, MessageVisible = true, Message = message } });
}
}
}
所以,当调用我的视图时,首先调用 "Index" 操作,但是当我 post 我的表单时,它也调用第一个索引方法。
此代码在旧版本中运行良好,新版本包含一些与此控制器无关的更改,但它不起作用,
当我在第一个操作中添加 HTTPGET 属性时,它工作正常,
第一个操作在页面加载时调用,第二个操作在页面 post.
上调用
所以,我的问题是路由是如何维护的 table 以及出现这种情况的原因是什么。
在您的 POST 操作中,将 [Route("Index/{exampleData?}")]
更改为 [Route("Index")]
,它应该会起作用。您没有将 POSTed 视图模型作为路线的一部分 - 想一想,它如何在 URL 中显示发布的数据?
我有一个控制器,其中定义了两个动作。
public class ExamlpeController : Controller
{
[Route("Index")]
public ActionResult Index()
{
return View(new ExampleViewModel { Message = new MessageDisplay { MessageVisible = false, IsGoodMessage = true, Message = String.Empty } });
}
// POST:
[HttpPost]
[Route("Index/{exampleData?}")]
public ActionResult Index(ExampleViewModel exampleData)
{
if (!ModelState.IsValid) // If model state is invalid
// Return view with validation summary
return View(new ExampleViewModel { Message = new MessageDisplay { MessageVisible = false, IsGoodMessage = true, Message = String.Empty } });
else // If model state is valid
{
// Process further
bool isGoodMessage = true; // Default
string message = "success";
isGoodMessage = true;
message = "test data";
// Clear model state if operation successfully completed
if (isGoodMessage)
ModelState.Clear();
return View(new ExampleViewModel { Message = new MessageDisplay { IsGoodMessage = isGoodMessage, MessageVisible = true, Message = message } });
}
}
}
所以,当调用我的视图时,首先调用 "Index" 操作,但是当我 post 我的表单时,它也调用第一个索引方法。
此代码在旧版本中运行良好,新版本包含一些与此控制器无关的更改,但它不起作用,
当我在第一个操作中添加 HTTPGET 属性时,它工作正常, 第一个操作在页面加载时调用,第二个操作在页面 post.
上调用所以,我的问题是路由是如何维护的 table 以及出现这种情况的原因是什么。
在您的 POST 操作中,将 [Route("Index/{exampleData?}")]
更改为 [Route("Index")]
,它应该会起作用。您没有将 POSTed 视图模型作为路线的一部分 - 想一想,它如何在 URL 中显示发布的数据?