我正在编写一个简单的MVC应用程序,其中我使用表单来放置一些数据,在我提交表单后,如果特定条件是false
我想再次显示表单,否则我会显示另一页。
当条件为假时,我做ReturnToAction("Form");
并且它完美地工作,但是,当条件为真且我RedirectToAction("MyPage");
时,我仍然看到表单,即使与表单提交相关的操作已经执行。
我错过了什么?谢谢
这是我的控制器
public class HomeController : Controller
{
private static bool condition = false;
public ActionResult Form()
{
return View();
}
[HttpPost]
public ActionResult CheckCondition(FormCollection form)
{
string username = form["txtUsername"];
condidion = true;
return RedirectToAction("MyPage");
}
public ActionResult MyPage()
{
if (!condition)
{
return RedirectToAction("Form");
}
else
{
return RedirectToAction("MyPage");
}
}
这是你的Form.aspx:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Form</title>
</head>
<body>
<form runat="server" method="post">
<ext:ResourceManager runat="server" />
<ext:Viewport runat="server" Layout="CenterLayout">
<Items>
<ext:FormPanel runat="server" id="Form" Url="/Home/CheckCondition"
Width="500"
Height="500"
Layout="CenterLayout"
>
<Items>
<ext:Window ID="Window1"
runat="server"
Closable="false"
Resizable="false"
Height="200"
Icon="Lock"
Title="Dashboard Login"
Draggable="false"
Width="350"
Modal="true"
BodyPadding="5"
Layout="FormLayout"
>
<Items>
<ext:TextField ID="txtUsername"
runat="server"
FieldLabel="Username"
AllowBlank="false"
BlankText="Your username is required."
Text="Demo" />
<ext:TextField ID="txtPassword"
runat="server"
InputType="Password"
FieldLabel="Password"
AllowBlank="false"
BlankText="Your password is required."
Text="Demo" />
</Items>
<Buttons>
<ext:Button ID="btnLogin" runat="server" Text="Login" Icon="Accept">
<Listeners>
<Click Handler="
if (!#{txtUsername}.validate() || !#{txtPassword}.validate()) {
Ext.Msg.alert('Error','The Username and Password fields are both required');
// return false to prevent the btnLogin_Click Ajax Click event from firing.
return false;
} else {
#{Form}.submit();
}" />
</Listeners>
</ext:Button>
</Buttons>
</ext:Window>
</Items>
</ext:FormPanel>
</Items>
</ext:Viewport>
</form>
</body>
</html>
答案 0 :(得分:0)
如果要显示相同的表单,则不应返回RedirectResult
。你应该调用View
方法。您还应该在处理表单提交的http post action方法中进行条件检查。
[HttpPost]
public ActionResult CheckCondition(FormCollection form)
{
if (someConditionCodeGoesHere==false) // replace this with your condition code
{
return View();
}
else
{
return RedirectToAction("Success");
}
}
public ActionResult Success()
{
return View();
}
将someConditionCodeGoesHere
替换为您的条件表达式的C#代码。尝试拥抱Stateless Http。在http调用之间保持状态的静态变量不是一个好主意。
还可以考虑使用视图模型在视图和操作方法之间传输数据。看看ASP.Net MVC How to pass data from view to controller
答案 1 :(得分:0)
我解决了这个问题。表单提交时出错,总是在失败时...我解决了这个问题并RedirectToAction
工作了。