2016-05-17 39 views
0

我想獲取數據並顯示每個循環內的數據。請在MVC中提供示例代碼完整的新手。是否有任何方法調用在Mvc Foreach循環內的方法

@foreach (var item in Model) 
    { 
     <tr> 
      <td> 
       @Html.DisplayFor(modelItem => item.cntryName) 
       //---- Here I want to call another method based on contryId and bind details 
       in another table 

      </td> 
+0

您並使用ajax並調用您的控制器,然後將結果解析到您的視圖。一些例子:http://www.binaryintellect.net/articles/218ca630-ba50-48fe-af6e-6f754b5894aa.aspx – freshbm

+0

http://stackoverflow.com/questions/22843324/calling-controller-action-method-directlyrom -razor-view – NnN

回答

1

可以編寫的HtmlHelper擴展

using System.Web.Mvc; 
namespace WebApplication1 
{ 
    public static class HtmlHelperExtensions 
    { 
     public static string YourTableEmittingMethod(this HtmlHelper helper, int countryId) 
     { 
     //Add your logic to create html string using the countryId 
     //and return string containing the Html tags for the table 
     } 
    } 
} 

,那麼你可以在你的MVC視圖中使用此方法,因爲@Html.YourTableEmittingCode(@item.CountryId)

瞭解更多關於HtmlExtensions here

+0

感謝您指點我正確的方向。我會做剩下的。 –

0

爲什麼不返回所有模型中需要的數據?

從發送到視圖的模型中,執行循環,以便返回到視圖的模型具有所需的所有數據。在您的cs文件中編寫您的邏輯代碼比在您的視圖中編寫要好得多。

相關問題