2013-03-11 77 views
2

我在mvc 4.0中提交了一個關於提交事件的表單。提交表單後發佈到其操作並創建記錄。創建記錄後,當我刷新頁面,然後創建另一個重複的記錄。如何防止在MVC中發佈表單後頁面刷新時數據庫中的重複條目

我已經使用下列但沒有成功:

ModelState.Clear(); 
ModelState.SetModelValue("Key", new ValueProviderResult(null, string.Empty, CultureInfo.InvariantCulture)); 
ModelState.Remove("Key"); 

我不希望使用AJAX形成後,也不想另一頁上重定向。

有沒有什麼辦法可以在asp.net中使用,例如在mvc4.0中的!Page.IsPostBack()

我不想使用會話也。 (微軟吹的MVC,MVC沒有任何視圖狀態像asp.net,但現在我不這麼認爲)。

+1

Page.IsPostBack並不妨礙這一點,即使你寫的代碼說!Page.IsPostBack,因爲瀏覽器重新完全相同requrest,這將是一個回傳,並再次插入記錄。 – 2013-03-11 13:37:45

+0

我要求解決方案!!Page.IsPostBack() – 2013-03-11 13:40:19

+0

狀態將在哪裏保存?瀏覽器在重新加載頁面時不會修改請求,我沒有會話,也沒有Cookie。所以你的服務器端永遠不會知道它是重複的。您必須寫入數據庫或重定向到某處,或將此狀態存儲在別處。 – Aneri 2013-03-11 13:48:16

回答

1

可以使用Ajax.post提交表單。像下面一樣構建你的表單標籤。

@using (@Html.BeginForm("Index", "ControllerName", FormMethod.Post, new { id = "anyFormName" })) 

從該頁面調用ajax帖子。

$.ajax({ 
     url: "/ControllerName/Index", 
     type: "POST", 
     data: $("#anyFormName").serialize(), 
     success: function (data) { 
      $("#divFormContainer").html(data); 
     } 
    }); 

在控制器中創建如下所示的Index方法。

[HttpPost] 
public ActionResult Index(FormCollection fc) 
{ 
    // Put the form post logics here.... 
    // Build the model for the view... 
    return PartialView("Index", model); 
} 
2

您可以在成功更新索引操作後重定向。在這種情況下,刷新將重新發送請求到索引操作,而不是發佈到更新操作。這種模式被稱爲「Post-Redirect-Get」模式。 例子:

[HttpPost] 
public ActionResult Update(SomeModelViewClass model) 
{ 
    //some code that save data to db 
    return RedirectToAction("index", new {id=model.Id}); 
} 

[HttpGet] 
public ActionResult Index(Guid id) 
{ 
    //some code that get data from db by id 
    return View(model); 
} 
相關問題