【发布时间】:2015-02-27 14:39:18
【问题描述】:
这个例子是人为的,我有一个部分视图,我通过页面上的 ajax 加载。局部视图上有一个下拉列表。如果我更改下拉列表的值,然后在控制器中重置该值。当局部视图再次加载(通过ajax)时,下拉列表没有正确获取设置值。
加载局部视图:
@model Test_PartailViews.Models.MyItemViewModel
@{
ViewBag.Title = "Home Page";
}
<div id="partialViewGoesHere">
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function(){
$.ajax({
url: '/Home/GetForm',
type: 'GET',
cache: false,
success: function (result) {
$('#partialViewGoesHere').html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + ':' + thrownError);
}
});
});
</script>
}
带有下拉列表的部分视图
@model Test_PartailViews.Models.MyItemViewModel
@using (Html.BeginForm("SaveForm", "Home", FormMethod.Post, new { id = "HomeForm" }))
{
<fieldset>
@Model.MyItemId
<div class="row">
<div class="col-sm-4 editor-field">
@Html.DropDownList("MyItemId", new SelectList(Model.ItemOptions, "Id", "Name", Model.MyItemId), "Select One...")
@Html.ValidationMessageFor(model => model.MyItemId)
</div>
</div>
<input type="submit" value="Submit" />
</fieldset>
}
<script type="text/javascript">
$('#HomeForm').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
cache: false,
success: function (result) {
// reload the partial view that is returned from post
$('#HomeForm').parent().html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
// show error occured
$('#HomeForm').parent().html(xhr.status + ':' + thrownError);
}
});
// show loading image when ajax call is made
$('#HomeForm').html('');
return false;
}); // $('form').submit
</script>
控制器:
public class HomeController : Controller
{
// Main page that has the partial view on it
[HttpGet]
public ActionResult Index()
{
MyItemViewModel model = new MyItemViewModel() { MyItemId = 1 };
return View(model);
}
// return partial view
[HttpGet]
public ActionResult GetForm()
{
// reset the id to 1
MyItemViewModel model = new MyItemViewModel() { MyItemId = 1 };
return PartialView("_MyItemPV", model);
}
// save partial view data
[HttpPost]
public ActionResult SaveForm(MyItemViewModel youModel)
{
return GetForm();
}
}
型号:
public class MyItemViewModel
{
public int MyItemId { get; set; }
public List<MyItem> ItemOptions {
get
{
List<MyItem> lst = new List<MyItem>();
lst.Add(new MyItem() { Id = 1, Name = "One" });
lst.Add(new MyItem() { Id = 2, Name = "Two" });
lst.Add(new MyItem() { Id = 3, Name = "Three" });
return lst;
}
}
}
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
}
当屏幕加载时,它显示 Id 为 1 并且下拉列表为“One”,正如预期的那样
将值更改为“二”并单击提交后。我希望 GetForm 方法将模型值重置为 1,并且下拉列表也将读取“一”。但是选择了“二”,即使 ID 为 1。
从提琴手查看结果后,我可以确认部分视图正在返回值“二”作为选择“。
任何帮助将不胜感激。
【问题讨论】:
标签: c# jquery asp.net asp.net-mvc razor