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.

tereško
  • 58,060
  • 25
  • 98
  • 150

1 Answers1

0

I refresh my partial views a little differently. I would use an ajax call on a button click instead of post back and pass the partial view that you want returned

$('.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);
        }
    });
});

Hopefully this will work for you.

Matt Bodily
  • 6,403
  • 4
  • 29
  • 48
  • i'm using it as jQuery ajax way same as you but problem is exist. That is updated about added or removed items but not for items that changed just in content. I don't know why. That is confused me. :( You can see my question about that in http://stackoverflow.com/questions/23033242/send-partial-view-model-and-update-partial-view-with-jquery-has-issues – QMaster Apr 13 '14 at 19:22