Asp.net-Mvc-3

根據 MVC3 中的下拉選擇載入部分視圖

  • September 11, 2013

我正在嘗試使用 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>

在下拉列表的更改事件中,通過 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 );
}

引用自:https://stackoverflow.com/questions/11774741