2015-04-06 39 views
0

我有控制器:RecruitmentController.cs 和我有方法/動作:cekrecomended如何在asp.net mvc c#中從視圖訪問類方法?

public string cekrecomended(string id) 
    { 
     id = EncryptDecrypt.Decrypt(id); 
     string ada = "false"; 
     string jurusan = Session["Jurusan"].ToString(); 
     string pendidikan = Session["Pendidikan"].ToString(); 
     int usia = Convert.ToInt16(Session["Usia"]); 
     string kelamin = Session["Kelamin"].ToString(); 
     double nilai = Convert.ToDouble(Session["Nilai"]); 
     var data = (from c in db.ViewVacancyJabatanPerusahaans 
        where 
         c.Pendidikan.Contains(pendidikan) && 
         (c.Jurusan.Contains(jurusan) || c.Jurusan.Contains("Semua jurusan")) && 
         c.Nilai <= nilai && 
         c.UsiaDari <= usia && 
         c.UsiaSampai >= usia && 
         c.JenisKelamin.Contains(kelamin) && 
         c.TglAkhirlamaran >= DateTime.Now && 
         c.Dlt == false && 
         c.IDVancancy == Convert.ToInt16(id) 
        orderby c.IDVancancy descending 
        select c).Count(); 
     if (data > 0) 
     { 
      ada = "true"; 
     } 
     return ada; 
    } 

我要訪問從視圖cekrecomended。

@if(Human_Resource_Development.Controllers.RecruitmentController.cekrecomended(Convert.ToString(item.IDVancancy)) == "true") 
{ 
    <button>Apply this position</button> 
} 

但我得到錯誤。

+1

你不應該這樣做 - 只要在你的視圖模型中顯示正確的計算屬性並使用它 – BrokenGlass 2015-04-06 02:32:47

回答

1

這使MVC的模型,視圖和控制器分離失敗 - 在您看來,您應該只使用視圖模型。在你的情況下,只需使用具有使該方法調用的結果可用的屬性的視圖模型。

1

您應該爲此目的使用您的視圖模型。比方說,MyViewModel是班級的模型,添加一個名爲IsRecommended

public class MyViewModel 
{ 
    // all of the other properties 
    // .... 

    public bool IsRecommended { get; set; } 
} 

設置的IsRecommended值在控制器的操作方法的布爾屬性

public ActionResult Index() 
{ 
    MyViewModel model = new MyViewModel(); 

    // other codes here 
    // ... 

    model.IsRecommended = ....; // logic from cekrecomended method here 

    return View(model); 
} 

確保您在頂部有這樣的語法您的視圖

@model MyViewModel 

並確定是否顯示「應用此位置」按鈕將根據IsRecommended財產如下

@if (Model.IsRecommended) 
{ 
    <button>Apply this position</button> 
} 
0

謝謝你的回答。我的問題解決了,我有解決方案。 我只是改變

public string cekrecomended(string id) 
{ 
    //bla bla 
} 

public static string cekrecomended(string id) 
{ 
    //bla bla 
} 

,我可以從視圖訪問。