【问题标题】:Load partial view depending on dropdown selection in MVC3根据 MVC3 中的下拉选择加载部分视图
【发布时间】:2012-07-31 06:19:47
【问题描述】:

我正在尝试使用 asp.net mvc3 创建一个。

我有一个包含一些选项的下拉列表。 我想要的是不同的局部视图被注入到页面中,这取决于下拉列表中的选择。

但是。我不希望这依赖于提交操作。它应该起作用,以便在您从选择列表中选择后立即加载局部视图。

我有这个代码:

@using (Ajax.BeginForm("Create_AddEntity", new AjaxOptions { 
    UpdateTargetId = "entity_attributes", 
    InsertionMode = InsertionMode.Replace
    }
))
{
        <div class="editor-label">
            @Html.Label("Type")
        </div>
        <div class="editor-field">
            @Html.DropDownList("EntityTypeList", (SelectList)ViewData["Types"])
        </div>

        <div id="entity_attributes"></div>
        <p>
            <input type="submit" value="Create" />
        </p>
}

但我不知道如何在下拉列表选择更改时触发此部分视图加载。

这点是不同“实体类型”的形式不同。因此将加载不同的局部视图,具体取决于下拉选择。

有人指点吗?

【问题讨论】:

  • 听起来你需要使用 Ajax 或 jQuery。

标签: asp.net-mvc-3 razor asp.net-ajax


【解决方案1】:

假设以下是您要插入部分视图的视图。

<html>
    <head><head>
    <body>
        <!-- Some stuff here. Dropdown and so on-->
        ....

        <!-- Place where you will insert your partial -->
        <div id="partialPlaceHolder" style="display:none;"> </div>
    </body>

</html>

在下拉列表的更改事件中,通过 jquery ajax 调用获取部分内容并将其加载到占位符。

/* This is change event for your dropdownlist */
$('#myDropDown').change( function() {

     /* Get the selected value of dropdownlist */
     var selectedID = $(this).val();

     /* Request the partial view with .get request. */
     $.get('/Controller/MyAction/' + selectedID , function(data) {

         /* data is the pure html returned from action method, load it to your page */
         $('#partialPlaceHolder').html(data);
         /* little fade in effect */
         $('#partialPlaceHolder').fadeIn('fast');
     });

});

在 jquery 上方的 /Controller/MyActionin 控制器操作中,返回您的部分视图。

//
// GET: /Controller/MyAction/{id}

public ActionResult MyAction(int id)
{
   var partialViewModel = new PartialViewModel();
   // TODO: Populate the model (viewmodel) here using the id

   return PartialView("_MyPartial", partialViewModel );
}

【讨论】:

  • 感谢您提供如此聪明的解决方案
  • 我知道这是一个旧答案。但是在使用这个解决方案时有什么方法可以将当前模型发送到局部视图
  • @AlexCarlsen 使用 selectedID 您还可以传递大量其他数据。也许您可以在视图中序列化当前模型并将其传递回服务器以部分操作方法。
  • @ emrenevayeshirazi另一方面,当所选索引为0时,无法触发JavaScript方法,并在屏幕上保持先前的HTML数据。如何解决?
  • @Christof 我不明白为什么当索引为 0 时不能运行 js。
【解决方案2】:

将以下代码添加到项目(布局)的标题中。 将“组合框”添加到要触发围绕它的表单的任何组合框(选择框)。

$(document).ready(function () {
    $('.formcombo').change(function () {
        /* submit the parent form */
        $(this).parents("form").submit();
    });
});

【讨论】:

  • 您不会将 formcombo 类添加到选择中,而不是组合框吗?不确定组合框来自哪里......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-21
  • 1970-01-01
  • 2018-10-19
相关资源
最近更新 更多