1

I have problems with PartialViews using ASP.NET MVC3 (Razor) and Ajax. This is my case:
I have simple test viewmodel:

public class MyModel
{
    public string MyText { get; set; }
    public int MyNumber { get; set; }
}

My target is to have a form. Depending on posted data I would like to display different partial views. I've created main form (Index view):

@using (Ajax.BeginForm("Index", "Test", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "testdiv" }))
{
    <div id="testdiv">


        @Html.Partial("Cat")

    </div>
    <input type="submit" value="Go" />
}

I've created two different partial views which should be shown when main form posted (depending on posted data): Cat View:

<span>cat view</span>
@Html.TextBoxFor(m=> m.MyText)
@Html.TextBoxFor(m=> m.MyNumber)
<span>@DateTime.Now.Second</span>

Dog View:

<span>dog view</span>
@Html.TextBoxFor(m=> m.MyText)
@Html.TextBoxFor(m=> m.MyNumber)
<span>@DateTime.Now.Second</span>

My controller contains four actions:

[HttpGet]
public ActionResult Index()
{
    MyModel model = new MyModel();
    return View(model);
}


[HttpPost]
public PartialViewResult Index(MyModel model)
{
    if (model.MyNumber == 1)
    {
        return Cat(model);
    }
    else
    {
        return Dog(model);
    }
}

[HttpPost]
public PartialViewResult Cat(MyModel model)
{
    model.MyText = model.MyText + " K";
    return PartialView("Cat", model);
}

[HttpPost]
public PartialViewResult Dog(MyModel model)
{
    model.MyText = model.MyText + " P";
    return PartialView("Dog", model);
}

My problem is that when Cat or Dog action is performed, MyText in model is changed, but when correct partial view is displayed I see old (not updated) MyText. Why? Any other ideas how to show a specific partial view depending on data posted in the form are welcome.

4

1 回答 1

0

我刷新了我的部分观点有点不同。我会在按钮单击时使用 ajax 调用而不是回发并传递您想要返回的部分视图

$('.btnSubmit').on('click', function(){
    $.ajax({
        url: "@(Url.Action("Action", "Controller"))",
        type: "POST",
        cache: false,
        async: true,
        data: { type: 'cat/dog' },
        success: function(result){
            $('.Content').html(result);
        }
    });
});

希望这对你有用。

于 2013-09-25T04:15:45.353 回答