2012-12-19 18 views
0

在我的獲取/索引視圖中我張貼到我的發佈/索引方法在holidayController。 所以我張貼在用戶名,我怎樣才能使用它來訪問用戶名?有userID在視圖中,需要userName張貼

㈣試圖

public ViewResult Index(int userID, string userName) 
     { 
      Person person = new Person(); 
      //this assigns person.Id to the user Id 
      person.Id = userID; 
      //i want to assign name of person to the string userName 
      userName = person.name; 
} 

這是閃動起來不能爲空值person.name?

+0

你爲什麼要這麼做?我認爲你在這裏是錯誤的方向... –

+0

你使用默認的內置aspnetdb? – garfbradaz

+0

@Pabloker,你是感謝您的答覆正確的,我是在錯誤的方向,使用LINQ我得到它到底:人的人(在db.People 從p其中p.Id == HolidayDate 選擇P)=。 FirstOrDefault(); userName = person.Name; – John

回答

0

你只需要初始化這個人的名字。

person.Name = userName 

但是我認爲,您所遇到的名稱不能爲空例外,因爲你有一個需要在Name屬性屬性,在Person類

,並可能是被傳遞給將用戶名行動是NULL


再次讀取的問題更新後:

您可以簡單地將用戶名保存到TempData或Session中,而不是在需要此數據的操作中進行訪問。

TempData["userName"] = person.Name; 

或者

Session["userName"] = person.Name; 


或者你可以將它保存到ViewBag或ViewData的,如果您需要爲您的視圖的數據。

ViewBag.UserName = person.Name 

或者

ViewData["userName"] = person.Name 
+0

請再讀一遍這個問題..他想給個人名字分配給字符串userName' –

+0

謝謝你指出。 ;) – CoffeeCode

+0

感謝您的答覆結束了LINQ排序 – John

0

string userName填寫?如果是這樣,如果它有一個公共setter,則可以使用person.Name = userName。如果字符串沒有填寫,你如何存儲這些對象?如果您使用數據庫,則可以使用您提供的ID在數據庫中查找Person對象。

+0

請閱讀問題again..he想'指定的人名串userName' –

+0

感謝您的答覆,是繞了錯誤的方式,結束了使用LINQ – John