【问题标题】:Loading a PartialView via ajax does not load dropdownlist selected item correctly通过 ajax 加载 PartialView 不会正确加载下拉列表中的选定项
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 这个答案可能是正确的。 View 将使用 ModelBinders 来设置值,然后再使用您传递的模型。这通常是你想要它做的,I.E.在出现错误时保留用户的输入,但有时它会咬你。清除 ModelState 将导致视图再次使用您的视图模型的值。
    • 虽然这可行,但通常不应使用它(清除 ModelState 也会清除验证错误)。而是遵循 RPG 模式(post 方法应该是return RedirectToAction("GetForm");
    【解决方案2】:

    您在 javascript 中返回 false。在这里——

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

    这应该是return true

    【讨论】:

    • 感谢您的回复,但是我返回 false 因为我不想发布整个页面,我只想在部分视图中的表单上执行 ajax 发布。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 2016-04-16
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多