这个例子是设计的,我有一个局部视图,我通过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,下拉列表为&#34; One&#34;正如所料
将值更改为&#34; 2&#34;并单击“提交”。我希望GetForm方法将模型值重置为1,并将下拉列表重置为&#34; One&#34;同样。但是&#34; Two&#34;即使Id为1,也会被选中。
从fiddler查看结果后,我可以确认部分视图正在返回值&#34; 2&#34;选中&#34;。
任何帮助都将不胜感激。
答案 0 :(得分:1)
之前我遇到过类似的问题,清除控制器中的ModelState对我来说是个窍门。您也可以清除ModelState中的特定值。
答案 1 :(得分:0)
你在javascript中返回false。这是 -
$('#HomeForm').html('');
return false;
这应该是返回true 。