I come from a more WPF
application background and I\'m used to bindings and such. Jumping into websites then can come with it\'s problems as they work so much more
Here's a full example.
Model:
public class MyViewModel
{
public int Year { get; set; }
public IEnumerable Years
{
get
{
return Enumerable.Range(1980, 40).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}
public IList Data { get; set; }
}
public class TheData
{
public int Year { get; set; }
public string Foo { get; set; }
public string Bar { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(int year)
{
var model = new[]
{
new TheData { Year = year, Foo = "foo 1", Bar = "bar 1" },
new TheData { Year = year, Foo = "foo 2", Bar = "bar 2" },
new TheData { Year = year, Foo = "foo 3", Bar = "bar 3" },
};
return PartialView("_data", model);
}
}
Index.cshtml
view:
@model MyViewModel
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "data" }))
{
@Html.DropDownListFor(x => x.Year, Model.Years, new { id = "yearsddl" })
}
Year
Foo
Bar
@Html.Partial("_data", Model.Data ?? Enumerable.Empty())
The jquery.unobtrusive-ajax.js
script inclusion should be moved out of the index view inside the layout for example and the custom js that subscribes for the change event of the dropdownlist should be moved into a separate js file and included from the Layout. I just put them here to illustrate a full example of what's required for the view to work.
_Data.cshtml
partial:
@model IList
@for (int i = 0; i < Model.Count; i++)
{
@Html.DisplayFor(x => x[i].Year)
@Html.DisplayFor(x => x[i].Foo)
@Html.DisplayFor(x => x[i].Bar)
}