@Html.BeginForm() 如何工作? [英] How does @Html.BeginForm() works?
问题描述
我对 ASP.NET 非常陌生,今天刚开始在 asp.net 上学习 MVC 教程.我到了这里 http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examing-the-edit-methods-and-edit-view
I'm very new to ASP.NET, just started the MVC tutorial today on asp.net. I got here http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-edit-methods-and-edit-view
到目前为止一切顺利,问题是:
So far so good, the problem:
在我的视图中,我有以下代码(模型设置为@model MyFirstMVC4.Models.Movie 的视图)
In my View I have the following code (Model is set to the view with @model MyFirstMVC4.Models.Movie)
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Movie</legend>
@Html.HiddenFor(model => model.ID)
//... bla bla html input
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
我的电影控制器
// Shows the view
public ActionResult Edit(int id = 0)
{
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return HttpNotFound();
}
return View(movie);
}
//
// POST: /Movie/Edit/5
[HttpPost] // Handles the view above
public ActionResult Edit(Movie movie)
{
if (ModelState.IsValid)
{
db.Entry(movie).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(movie);
}
这里有一个问题——它到底是如何将 Movie 对象传递给上面的 POST 方法的?!当我观察客户端时有
And here is the question - How the heck does it pass the Movie object to the POST method above?! When I observe the client side there is
<form action = "/Movie/Edit/1" ... />
这里我不明白为什么 action = url 是同一个视图页面?!1同样在服务器端只有 Html.BeginForm() :(它是如何实现向什么动作方法发布以及要传递什么路由参数的?它有效,我只是不知道为什么
Here I don't understand why action = url of the very same view page?!1 Also on the server side there is just Html.BeginForm() :( How does it realize to what action method to post and what route parameters to pass? It works, I just don't know why
推荐答案
代码中BeginForm
的版本,不带参数,向当前 URL 发送一个 HTTP POST,所以如果视图是对/Movie/Edit/5
,打开表单标签如下所示:<代码>