我来自更多的 WPF
应用程序背景,我习惯于绑定(bind)等。然后跳入网站可能会带来问题,因为它们的工作方式大不相同。
我正在尝试做一个简单的 Ajax
操作,但不知道从哪里开始。基本上,我想创建一个下拉列表来更改模型上的一个属性并重新呈现页面的该部分。也许这是一种太多的 WPF 方式来执行此操作,因此我的模型可能会因为它应该做的事情而被扭曲。
这是我已经得到的:
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
}
还有 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>
如您所见,我希望更新 Year 属性并为 Data 属性进行新调用,这将产生新信息。该信息将在 thetable
Table
最佳答案
这是一个完整的例子。
型号:
public class MyViewModel
{
public int Year { get; set; }
public IEnumerable<SelectListItem> Years
{
get
{
return Enumerable.Range(1980, 40).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}
public IList<TheData> 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
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#yearsddl').change(function () {
$(this).closest('form').trigger('submit');
});
});
</script>
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "data" }))
{
@Html.DropDownListFor(x => x.Year, Model.Years, new { id = "yearsddl" })
}
<table>
<thead>
<tr>
<th>Year</th>
<th>Foo</th>
<th>Bar</th>
</tr>
</thead>
<tbody id="data">
@Html.Partial("_data", Model.Data ?? Enumerable.Empty<TheData>())
</tbody>
</table>
jquery.unobtrusive-ajax.js
脚本包含应移出布局内的索引 View ,例如,订阅下拉列表的更改事件的自定义 js 应移入一个单独的 js 文件并包含在布局中。我只是将它们放在这里以说明 View 工作所需的完整示例。
_Data.cshtml
部分:
@model IList<TheData>
@for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>@Html.DisplayFor(x => x[i].Year)</td>
<td>@Html.DisplayFor(x => x[i].Foo)</td>
<td>@Html.DisplayFor(x => x[i].Bar)</td>
</tr>
}
关于ajax - asp.net MVC 3中的简单Ajax,更新模型并重新渲染部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9465475/