1

I am not sure if I am overlooking something obvious. Once I do a POST, I have the following (Note: What I am trying to do is to default the same view with some null values so the user can create another entry):

    [HttpPost]
    public ActionResult QkInsert(ProgInfo model)
    {

        if (ModelState.IsValid)
        {
            ProgService.InsertQuickEntry(model);


            model.Name = null;
            model.Address = null;
            model.Phone = null;            

            return view(model);


        }

         return view(model);

What is strange is that when I look at the value of model in the IsValid()

    return view(model) 

I do see the null values. But when it is shown on the view, it is not null. It is basically the same view as when I had entered the data the first time. Any idea? Have I overlooked something?

Also notice how I have done return view(model) twice. Is there any other way of doing this to where I do it only once and not repeat?

1
  • You don't need the return inside the if statement Commented Oct 18, 2012 at 18:02

2 Answers 2

2

That's because HTML helpers are first looking into the ModelState when binding their values and only after that the value in your model. This is by design.

So if you want to change any value of the model inside a POST action you need to remove it from the ModelState first:

[HttpPost]
public ActionResult QkInsert(ProgInfo model)
{
    if (ModelState.IsValid)
    {
        ProgService.InsertQuickEntry(model);

        ModelState.Remove("Name");
        ModelState.Remove("Address");
        ModelState.Remove("Phone");
        model.Name = null;
        model.Address = null;
        model.Phone = null;            

        return view(model);
    }

    ....
}

Now the view will render the modified values.

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

Comments

1

If the model is not valid you will return the same model, your second return.

There is no need at all for the first return view(model) as there is no code between it and the second one, so it will call anyway. That is, delete the first return and the logic is identical.

2 Comments

Don't know who -1'd you but +1 for the tip! :)
@dove - Thanks but the thing is that it was a valid model and still it returned the same model even though I said for it to make certain values null

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.