Rendering same View after Http Post in MVC

2019-05-10 13:00发布

问题:

Trying to repost a view but im getting null to the field I want.

Heres the controller...

    public ActionResult Upload()
    {
        VMTest vm = new VMTest();
        return View(vm);
    }

    [HttpPost]
    public ActionResult Upload(VMTest vm, String submitButton)
    {
        if (submitButton == "Upload")
        {
            //do some processing and render the same view
            vm.FileName = "2222";           // dynamic creation of filename
            vm.File.SaveAs(@vm.FileName);   // save file to server
            return View(vm);
        }
        else if (submitButton == "Save")
        {
            //read the file from the server
            FileHelperEngine engine = new FileHelperEngine(typeof(PaymentUploadFile));
            PaymentUploadFile[] payments = (PaymentUploadFile[])engine.ReadFile(@vm.FileName);  // the problem lays here @vm.FileName has no value during upload

            //save the record of the file to db
            return View("Success");
        }
        else
        {
            return View("Error");
        }
    }

I already had a @Html.HiddenFor(model => Model.FileName) inside my view.

But still I got a null value for Model.FileName.

Any help pls

Thanks

回答1:

If you intend to modify some values of your view model in the POST action you need to remove the old value from modelstate first:

ModelState.Remove("FileName");
vm.FileName = "2222"; 

The reason for this is that Html helpers such as TextBox, Hidden, ... will first use the value in the modelstate when binding and after that the value in your view model.

Also instead of:

@Html.HiddenFor(model => Model.FileName)

you should use:

@Html.HiddenFor(model => model.FileName)

Notice the lowercase m in the expression.



回答2:

The above answer is a good one. You can also do the following

public ActionResult Upload()
{
    VMTest vm = new VMTest();

    ModelState.Clear();

    return View(vm);
}

I usually call ModelState.Clear() before loading a new view. The sytntax for HiddenFor should be

@Html.HiddenFor(m => m.FileName);

I hope this helps.