3

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

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much.. Id been spending a couple of days to resolve this one.. only ModelState.Remove is the key ... thanks @Darin
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.