Reputation: 666
I am submitting a form on submit event in mvc 4.0. after submitting form is posted to its action and record is created. after creating record when i refresh the page then another duplicate record is created.
I already used following but not succeed:
ModelState.Clear();
ModelState.SetModelValue("Key", new ValueProviderResult(null, string.Empty, CultureInfo.InvariantCulture));
ModelState.Remove("Key");
I don't want to use AJAX form Post and also don't want to redirect on another page.
Is there any way that we use in asp.net like !Page.IsPostBack()
in mvc4.0.
I dont want to use session also.
(Microsoft blowing about MVC that MVC does not have any view state like asp.net but now I don't think so).
Upvotes: 2
Views: 3175
Reputation: 1774
You can submit the form using Ajax.post. Construct your form tag like below.
@using (@Html.BeginForm("Index", "ControllerName", FormMethod.Post, new { id = "anyFormName" }))
Call the ajax post from the page.
$.ajax({
url: "/ControllerName/Index",
type: "POST",
data: $("#anyFormName").serialize(),
success: function (data) {
$("#divFormContainer").html(data);
}
});
In controller create the Index method like below.
[HttpPost]
public ActionResult Index(FormCollection fc)
{
// Put the form post logics here....
// Build the model for the view...
return PartialView("Index", model);
}
Upvotes: 1
Reputation: 11964
You can redirect after succesful update to index action. In this case refresh will resend request to index action instead post to update action. This pattern is known as "Post-Redirect-Get" pattern. Example:
[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);
}
Upvotes: 2