根据MVC3中的下拉选择加载部分视图



我正在尝试使用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>
}

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

这一点是,对于不同的"实体类型",形式是不同的。因此,根据下拉选择,将加载不同的局部视图。

有人有什么线索吗?

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

<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>

在dropdownlist的更改事件中,通过jquery ajax调用获取partial并将其加载到占位符。

/* 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/MyActions,返回您的部分视图。

//
// 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 );
}

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

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

最新更新