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 differently.
I'm trying to do a simple Ajax
action but not sure where to begin. Basically I want to make a dropdownlist that changes one property on the model and re-renders that part of the page. Perhaps this is too much of a WPF way to do this so my Model could be twisted for the thing it is supposed to do.
Here is what I got already:
public class TheViewModel
{
private IEnumerable<TheData> _data;
public TheViewModel(IEnumerable<TheData> data)
{
_data = data;
Year = 2012;
}
public int Year { get; set; }
public ICollection<TheData> Data
{
get
{
return _data.Where(d => d.Year == this.Year).ToList();
}
}
public IEnumerable<SelectListItem> YearList
{
// lists the available years
}
}
public class TheData
{
public int Year { get; set; }
//Some more info I want to represent in Table
}
And the razor:
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "thetable" }))
{
@Html.DropDownListFor(model => model.Year, Model.YearList, new { AutoPostBack = "true"})
<input type="submit" name="name" value="Submit" />
}
<table id="thetable">
<thead>
//some headers
</thead>
<tbody>
@foreach ( var item in Model.Data)
{
//row for each data
}
</tbody>
</table>
As you can see I'm hoping for the Year property to be updated and a new call to be made for the Data property which would result in new information. That information would be rendered in thetable
Table
Here's a full example.
Model:
Controller:
Index.cshtml
view: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: