开发者

RenderPartial via Ajax(jquery) and renders with incorrect model. (BUG)?

I've got a really unusual issue where even though the debugger claims to be rendering the partial view with new newly created model in the controller, it renders it with the model values from the data that was passed in from the post.

A modelstate.clear(); fixes the issue but surely this is not correct.

Any ideas?

Calling Script

$("#registerSubmit").live("click", function (e) {
            if ($("#registerForm").valid()) {
                $.ajax({
                    url: 'home/Register',
                    data: $("#registerForm").serialize(),
                    type: 'POST',
                    success: function (data) {
                        alert(data);
                        $("#registerHolder").html(data);
                    }
                });
            }
            e.preventDefault();
        });

Controller

[HttpPost]
        public ActionResult Register(Register model)
        {
            var t = new Register();
            t.EmailAddress = "test";
            t.Password = "1";
            t.VerifyPassword = "2";

            return 开发者_Go百科PartialView("p_register2", t);
        } 


If you want to modify values that are being POSTed you will need to remove them from the model state or HTML helpers will always use the POSTed values and not the ones in your model. That's how HTML helpers work and this behavior is by design. For example a Html.TextBoxFor(x => x.EmailAddress) helper sees that there is a POSTed EmailAddress value and it will use this value instead of the one you are passing in the model.

So, you should either remove the values that you want to modify from the model state or write your own HTML helpers:

[HttpPost]
public ActionResult Register(Register model)
{
    var t = new Register();
    t.EmailAddress = "test";
    t.Password = "1";
    t.VerifyPassword = "2";
    ModelState.Remove("EmailAddress");
    ModelState.Remove("Password");
    ModelState.Remove("VerifyPassword ");
    return PartialView("p_register2", t);
} 

and looking at this action one might ask himself the question: what's the purpose of the Register model you are using as action argument? So:

[HttpPost]
public ActionResult Register()
{
    var t = new Register();
    t.EmailAddress = "test";
    t.Password = "1";
    t.VerifyPassword = "2";
    return PartialView("p_register2", t);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜