2
votes

I'm having a simple action:

 [HttpPost]
    public virtual ActionResult New(Feedback feedback)
    {
        feedback.CreatedDate = DateTime.UtcNow;

        if (TryValidateModel(feedback))
        {
            FeedbackRepository.Add(feedback);
            var model = new Feedback
                            {                                   
                                SuccessfullyPosted = true
                            };

            return PartialView(MVC.Shared.Views._FeedBackForm, model);
        }

        return PartialView(MVC.Shared.Views._FeedBackForm, feedback);
    }

So, idea is if received data is validating fine, return partial view with empty feedback entity. Thing is, that if i look at firebug response, I see old values coming back, how weird is this?

Form looks like this:

@using (Ajax.BeginForm(MVC.Feedback.New(), new AjaxOptions
                                                                 {
                                                                     UpdateTargetId = "contactsForm",
                                                                     HttpMethod = "post"
                                                                 }))
{           
    
        

@Html.LabelFor(x => x.FirstName) @Html.EditorFor(x => x.FirstName) @Html.ValidationMessageFor(x => x.FirstName)

@Html.LabelFor(x => x.LastName) @Html.EditorFor(x => x.LastName) @Html.ValidationMessageFor(x => x.LastName)

@Html.LabelFor(x => x.Email) @Html.EditorFor(x => x.Email) @Html.ValidationMessageFor(x => x.Email)

@Html.LabelFor(x => x.Phone) @Html.EditorFor(x => x.Phone) @Html.ValidationMessageFor(x => x.Phone)

@Html.LabelFor(x => x.Comments)
@Html.TextAreaFor(x => x.Comments, new { cols = 60, rows = 10 }) @Html.ValidationMessageFor(x => x.Comments)

if (Model.SuccessfullyPosted) { Feedback sent successfully. }

}

Is it possible somehow to disable this behavior and how PartialView(MVC.Shared.Views._FeedBackForm, model) manages to get different model?

update: I see stackoverflow ate all html from by view and can't find how to fix that.

1

1 Answers

4
votes

ModelState is primary supplier of model values. Even if you pass your model to View or PartialView, EdiorFor will first look into ModelState for corresponding property value, and if it does not exist there, only then into model itself. ModelState is populated when posting to controller (old feedback). Even if you create new feedback and pass it as model, ModelState already contains values from previously posted feedback, so you get old values on client. Clearing modelstate before successfull post result will help you.

FeedbackRepository.Add(feedback);
var model = new Feedback
                {                                   
                   SuccessfullyPosted = true
                 };
ModelState.Clear(); // force to use new model values
return PartialView(MVC.Shared.Views._FeedBackForm, model);

See this and this links for examples of related situations