mvc學習-編輯提交需要注意-mvc重點
示例程式碼:
// GET: /Movies/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(movie); }// POST: /Movies/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include="ID,Title,ReleaseDate,Genre,Price")] Movie movie) {if (ModelState.IsValid) { db.Entry(movie).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(movie); }
注意下面的程式碼:Bind(Include="ID,Title,ReleaseDate,Genre,Price")] Movie movie 第一次見,發現可以這樣寫。
連結:https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application#overpost
請注意第二個 Edit
操作方法的前面是 HttpPost
特性。 此屬性指定的過載Edit
可以僅針對發出的 POST 請求呼叫方法。 您可以應用HttpGet
屬性與第一個編輯方法,但是,它們是不必要,因為它是預設值。 (我們將引用的操作方法的隱式分配HttpGet
屬性為HttpGet
方法。)繫結屬性是黑客可以防止過度釋出到您的模型資料的另一個重要的安全機制。 在你想要更改的繫結屬性中,應僅包含屬性。 你可以閱讀過多釋出和中的繫結屬性我過多釋出安全說明。 在本教程中使用簡單模型中,我們將繫結模型中的所有資料。 ValidateAntiForgeryToken屬性用於防止請求偽造,並使用成對出現@Html.AntiForgeryToken()
在編輯檢視檔案 (Views\Movies\Edit.cshtml),如下一部分所示:
@Html.AntiForgeryToken()
生成必須匹配隱藏的窗體防偽令牌Edit
方法的Movies
控制器。你可以閱讀更多有關跨站點請求偽造 (也稱為 XSRF 或 CSRF) 在我的教程MVC 中的 XSRF/CSRF 防護。
https://docs.microsoft.com/zh-cn/aspnet/mvc/overview/getting-started/introduction/examining-the-edit-methods-and-edit-view
這個教程有關於驗證資訊國際的部分,需要認真學習下。
同事教程內容非常豐富,需要多看看。