Search code examples
c#asp.net-mvc-3partialviews

Fields still contain form data when new model instance is passed to partial view


I have a partialview which post to server using jquery. The posting is working. However, when returning, I am returning partialviewresult with blank model (new model), but the return HTML is still containing the data previously post. Any idea on clearing the data on the return?

$("#btnSend").click(function (e) {
    e.preventDefault();

    if($('#frmCompose').valid()) {
        $.ajax({
            type: "POST",
            url: '@Url.Action("PartialCompose", "Message")',
        dataType: "html",
        data: $('#frmCompose').serialize(),
        success: function (result) {
            $("#divTab2").html(result);
        },
        error: function (xhr, s, e) {
            alert('Error');
            alert(xhr.responseText);
        }
        });
    }        
});

Here is the Action:

    [SessionExpireFilterAttribute]
    [HttpPost] // POST: /message/partialcompose
    public PartialViewResult PartialCompose(_MessageExt model)
    {
        _MessageExtDAL __DAL = new _MessageExtDAL(base.LoginTimeZoneMin);
        try
        {
            model.MessageId = 0;
            model.AccountId = base.LoginUser.AccountId;
            model.EditBy = base.LoginUser.UserId;

            __DAL.Send(model, Config.SQLConn);
        }
        catch (Exception ex)
        {
            base.Prompt = ex.Message;
        }
        finally
        {
            __DAL = null;
        }
        return PartialView(new _MessageExt());
    }

Solution

  • This is due to the fact that you are returning the same view directly from the POST action and the form values still exist in ModelState.

    This is by design, primarily for the purpose of displaying validation errors in conjunction with the original form data. Values in ModelState have a higher precedence than those in the model object passed to the view, so if both exist, the values in ModelState will be used.

    The following should see the fields cleared:

    ModelState.Clear();
    return PartialView(new _MessageExt());