I have an form with following url: CreateEntity?officeCodeId=5
When I send form to validate and if validation is fail it returns just CreateEntity u
Your actions should looks like this:
Actions:
[HttpGet]
public virtual ActionResult CreateEntity(int? officeCodeId)
{
var model = new CreateViewModel();
FillViewModel(model, officeCodeId);
return View("Create", model);
}
[HttpPost]
public virtual ActionResult CreateEntity(ViewModel model)
{
if (model.IsValid) {
// save...
return RedirectToAction("EditEntity", newId!!!);
}
return View("Create", model);
}
Html:
@using (Html.BeginForm()) {
@Html.HiddenFieldFor(m => Model.officeCodeId)
...
}
Your officeId should be in model. And on html form you can store it in hidden field.
Your final answer is excellent and works great, although you can further enhance it to make it more generic by simply including Request.QueryString
:
<form action="@Url.Action("CreateEntity", "Employee")?@(Request.QueryString)"
enctype="multipart/form-data" method="POST">
Then use the POST
action:
[HttpPost]
protected virtual ActionResult CreateEntity(TEditViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
The problem is your HttpPost
action doesn't have any notion of an id
parameter. If you want to support a similar URL then make the action signature support that parameter e.g.
[HttpGet]
public ActionResult CreateEntity(int? officeCodeId)
[HttpPost]
public ActionResult CreateEntity(int officeCodeId, EditViewModel model);