使用ASP.net MVC执行提交(回发)和重定向

本文关键字:回发 重定向 提交 ASP net MVC 执行 使用 | 更新日期: 2023-09-27 18:29:41

我想在标记中使用submit,以实现ASP.net MVC操作。

然后我想将请求重定向到另一个url。

我可以这么做吗?或者MVC只对应ajax?

使用ASP.net MVC执行提交(回发)和重定向

如果你使用的是Html.BeginForm,那么帖子就会出现

<% using(Html.BeginForm("HandleForm", "Home")) { %>
    <fieldset>
        <legend>Fields</legend>
        <p>
            <%= Html.TextBoxFor(m => m.Field1) %>
        </p>
        <p>
            <%= Html.TextBoxFor(m => m.Field2) %>
        </p>
        <p>
            <input type="submit" value="Submit" />
        </p> 
    </fieldset>
<% } %>

然后您的控制器操作可以执行重定向:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult HandleForm(MyModel myModel)
{
    // Do whatever you need to here.
    return RedirectToAction("OtherAction", myModel);
}
public ActionResult OtherAction(MyModel myModel)
{
    return View(myModel);    
}

编辑::上面的示例现在将与以下模型绑定,并且可以在操作之间传递:

public class MyModel
{
    public string Field1 { get; set; }
    public string Field1 { get; set; }
}

下面的代码演示了如何在用户提交表单后将其重定向到另一个操作。

如果您想保留任何提交的数据以供重定向到的操作方法使用,则需要将其存储在TempData对象中。

public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        // Get the e-mail address previously submitted by the user if it
        // exists, or use an empty string if it doesn't
        return View(TempData["email"] ?? string.Empty);
    }
    [HttpPost]
    public ActionResult Index(string email)
    {
        // Store the e-mail address submitted by the form in TempData
        TempData["email"] = email;
        return RedirectToAction("Index");
    }
}

你的Index视图看起来像这样:

@using (Html.BeginForm("Index", "Home"))
{
    @* Will populate the textbox with the previously submitted value, if any *@
    <input id="email" type="email" name="email" value="@Model" />
    <button type="submit">Submit</button>
}