簡體   English   中英

MVC如何處理控制器中的按鈕點擊

[英]How does MVC handle button clicks in the controller

MVC如何處理我的代碼中的提交按鈕? 我有一個名為ArticleController的控制器應該處理它,但我無法弄清楚如何。

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Article</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Text, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Text, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Text, "", 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>
}

<div>
  @Html.ActionLink("Back to List", "Index")
</div>

控制器看起來像這樣:

namespace Decision.Controllers
{
  public class ArticleController : Controller
  {
    // GET: Article
    public ActionResult Index()
    {
        return View();
    }
    [HttpGet]
    public ActionResult Create()
    {
        var article = new ArticleController();
        var home = new HomeController();
        return View(home);
    }

    /*[HttpPost]
    public ActionResult Create(Article article)
    {
        entities.Article.AddObject(article);
        entities.SaveChanges();

        return Redirect("/");
    }*/
  }
}

單擊時哪個方法處理提交按鈕?

HttpPost控制器通常會處理它,但你出於某種原因已經注釋掉了嗎? 您需要使用一些信息標記BeignForm,即

@using (Html.BeginForm("Create", "Article", FormMethod.Post, new { @class = "insert any css class here", role = "form" }))
{ 

因此,在純HTML中,您需要在具有post方法的表單中包含提交按鈕。

 <form action = "" method = "post">
        <input type="submit" name="x" value="x" />
 </form>

BeginForm擴展默認使用post方法。

public static MvcForm BeginForm(
    this HtmlHelper htmlHelper
)

要了解如何使用BeginForm擴展,您可以在這里閱讀更多內容: @ Html.BeginForm()如何工作?

您的主要問題如下:

要了解@using(Html.BeginForm())如何工作,您需要知道它已經在哪個頁面。 在2個不同的視圖中使用@using(Html.BeginForm())將返回兩個不同的控制器

首先,您可以在渲染表單時檢查HTML中生成的操作: <form action = "" method = "post">

然后你必須知道你有可能將執行的動作/控制器傳遞給BeginForm擴展方法。

例如:

@using (Html.BeginForm("Create", "Article", FormMethod.Post))
{
  @* *@ 
}

請查看https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods以獲得有關請求方法的清晰概念。

當用戶查看頁面時,這是一個GET請求,當用戶提交表單時,通常是一個POST請求。 HttpGet和HttpPost只是將操作限制為適用的請求類型。

當您將[HttpPost]添加到操作時,MVC清楚地知道要使用哪個操作來處​​理POST請求。

好像你在索引視圖中。 您需要將BeginForm更改為

@using (Html.BeginForm("Create","Article")) 
{
    <<your stuff>>
}

並取消注釋后方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM