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.