Query string param is missed when form validation fail

前端 未结 3 1435
后悔当初
后悔当初 2020-12-21 06:22

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

相关标签:
3条回答
  • 2020-12-21 06:31

    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.

    0 讨论(0)
  • 2020-12-21 06:42

    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);
        }
    
    0 讨论(0)
  • 2020-12-21 06:50

    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);
    
    0 讨论(0)
提交回复
热议问题