通过 ajax 加载 PartialView 不会正确加载下拉列表中的选定项目

Loading a PartialView via ajax does not load dropdownlist selected item correctly

这个例子是人为设计的,我有一个部分视图,我通过页面上的 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,下拉列表如预期的那样为“一个”

将值更改为“二”并单击提交后。我希望 GetForm 方法将模型值重置为 1,并且下拉列表也显示为“一”。但是选择了“二”,即使 Id 为 1。

查看 fiddler 的结果后,我可以确认分部视图返回的是所选值“two”。

如有任何帮助,我们将不胜感激。

你 return 你的 javascript 是假的。这是 -

$('#HomeForm').html('');

return false;

这应该是 return 正确的

我之前遇到过类似的问题,清除控制器中的 ModelState 对我来说是个窍门。您也可以只清除 ModelState 中的特定值。