簡體   English   中英

將int數組傳遞給MVC Controller

[英]Passing an int array to MVC Controller

我正在嘗試將一個int數組從JavaScript傳遞給一個接受2個參數的MVC控制器 - 一個int數組和一個int。 這是執行頁面重定向到Controller Action返回的視圖。

var dataArray = getAllIds(); //passes back a JavaScript array 
window.location.replace("/" + controllerName + "/EditAll?ids=" + dataArray + "&currentID=" + dataArray[0])

dataArray包含1,7個我的樣本用法。

控制器代碼

public virtual ActionResult EditAll(int[] ids, int currentID)
{

  currentModel = GetID(currentID);
  currentVM = Activator.CreateInstance<ViewModel>();
  currentVM.DB = DB;
  currentVM.Model = currentModel;
  currentVM.ViewMode = ViewMode.EditAll;
  currentVM.ModelIDs = ids;

  if (currentModel == null)
  {
      return HttpNotFound();
  }

  return View("Edit", MasterName, currentVM);
}

問題是當檢查傳遞給控制器​​的int [] id時,它的值為null。 currentID按預期設置為1。

我已經嘗試設置jQuery.ajaxSettings.traditional = true這沒有效果我也嘗試在JavaScript中使用@ Url.Action創建服務器端URL。 在傳遞數組之前我也嘗試過JSON.Stringify

window.location.replace("/" + controllerName + "/EditAll?ids=" + JSON.stringify(dataArray) + "&currentID=" + dataArray[0])

同樣,id數組在控制器端最終為null。

有沒有人有任何關於讓int數組正確傳遞給控制器​​的指針? 我可以在Controller Action中將參數聲明為String並手動序列化和反序列化參數,但我需要了解如何讓框架自動執行簡單的類型轉換。

謝謝!

要在MVC中傳遞一組簡單值,您只需要為多個值賦予相同的名稱,例如,URI最終會看起來像這樣

/{controllerName}/EditAll?ids=1&ids=2&ids=3&ids=4&ids=5&currentId=1

MVC中的默認模型綁定將正確地將其綁定到int數組Action參數。

現在,如果它是一個復雜值的數組,則可以采用兩種方法進行模型綁定。 我們假設您有類似的類型

public class ComplexModel
{
    public string Key { get; set; }

    public string Value { get; set; }
}

和控制器動作簽名

public virtual ActionResult EditAll(IEnumerable<ComplexModel> models)
{
}

對於正確的模型綁定,值需要在請求中包含索引器,例如

/{controllerName}/EditAll?models[0].Key=key1&models[0].Value=value1&models[1].Key=key2&models[1].Value=value2

我們在這里使用的是一個int索引器,但你可以想象這在一個應用程序中可能非常不靈活,在這個應用程序中,可以在集合中的任何索引/插槽中添加和刪除在UI中呈現給用戶的項目。 為此,MVC還允許您為集合中的每個項目指定自己的索引器,並將該值傳遞給默認模型綁定的請求以使用,例如

/{controllerName}/EditAll?models.Index=myOwnIndex&models[myOwnIndex].Key=key1&models[myOwnIndex].Value=value1&models.Index=anotherIndex&models[anotherIndex].Key=key2&models[anotherIndex].Value=value2

在這里,我們為模型綁定指定了自己的索引器myOwnIndexanotherIndex用於綁定復雜類型的集合。 據我所知,您可以為索引器使用任何字符串。

或者,您可以實現自己的模型綁定器來指示傳入請求應如何綁定到模型。 這需要比使用默認框架約定更多的工作,但確實增加了另一層靈活性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM