c# - 当新模型实例传递给局部 View 时,字段仍然包含表单数据

标签 c# asp.net-mvc-3 partialviews

我有一个使用 jquery 发布到服务器的局部 View 。发布工作正常。但是,返回时,我返回带有空白模型(新模型)的 partialviewresult,但返回的 HTML 仍包含之前发布的数据。关于清除返回数据的任何想法?

$("#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);
        }
        });
    }        
});

这是 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());
    }

最佳答案

这是因为您直接从 POST 操作返回相同的 View ,并且表单值仍然存在于 ModelState 中。

这是设计使然,主要是为了与原始表单数据一起显示验证错误。 ModelState 中的值比传递给 View 的模型对象中的值具有更高的优先级,因此如果两者都存在,则 ModelState 中的值将是用过。

以下应该看到清除的字段:

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

关于c# - 当新模型实例传递给局部 View 时,字段仍然包含表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24806628/

相关文章:

jquery - JQuery 如何使用模型?

asp.net-mvc-3 - MVC 3 with Razor 关于部分 View 的问题

asp.net-mvc - 在 MVC 中呈现局部 View

c# - 比较数组的一种方法

c# - 有没有更有效的方法将这些平面数据放入字典中?

c# - 通过 TempData 传递 ViewModel?

c# - "SetCertificatePath"C# 物联网设备客户端中的选项

c# - 使用 IoC 解析 Action Methods 中的模型对象

c# - 如何解决循环依赖