2011-10-10 256 views
1

如果您將匿名對象傳遞迴控制器,它會通過查看匿名對象屬性名稱來填充控制器參數 - 那麼如何將相關對象的屬性傳回給我的模型,以便默認值綁定可以綁定他們?ASP .NET MVC 3 - 將參數從視圖傳遞到控制器

例如:

型號:

public class MyViewModel 
{ 
    public MyItem MyItem { get; set; } 
} 

public class MyItem 
{ 
    public string Name { get; set; } 
} 

控制器:

public ActionResult Index(MyViewModel model) 
{ 
    return View(model); 
} 

在視圖中,我想通過MyItem.Name回來了,這怎麼可能?我曾嘗試:

@Html.ActionLinke("Index", "MyController", new { name = "example" }) 

@Html.ActionLinke("Index", "MyController", new { myItem_Name = "example" }) 

請幫助!

回答

0

答案是創建一個自定義ModelBinder和ModelBinderProvider。

1

您可以使用以下過載:

@Html.ActionLink( 
    "link text",        // linkText 
    "Index",         // actionName 
    "MyController",       // controllerName 
    new RouteValueDictionary {    // routeData 
     { "MyItem.Name", "example" } 
    }, 
    null          // htmlAttributes 
) 
+0

不錯的想法,但不行,我害怕。 – PeteGO

2

你試過:

@Html.ActionLink("Index", "MyController", new { name = @Model.MyItem.Name }) 

而且在操作方法:

public ActionResult Index(string name) 
{ 
    return View(); 
} 
+0

我知道我可以這樣做,但我認爲默認模型聯編程序可以處理繼承,所以我必須有一個參數是我的視圖模型對象。 – PeteGO

1

我想你可能誤解「了將對象從視圖傳遞給控制器​​'。 這不是你傳遞對象 - 你只是在頁面中呈現一個鏈接(錨定標記)。當用戶點擊鏈接時,請求實際上來自瀏覽器。沒有'服務器端對象傳遞'正在進行。

鏈接必須包含服務器端(在控制器中)需要的所有參數作爲查詢字符串參數。

我認爲你真正想要做什麼或者是:

  1. 呈現一個表格並提交,或

  2. 通只有你所需要的數據的ID,並在控制器檢索它(例如從DB)

相關問題