2014-10-07 38 views
0

我有這樣的:編輯userPropfile asp.net mvc4

控制器動作:

public ActionResult Edit(int id = 0) 
{ 
     UserProfile user = db.SelectByID(id); 
     return View(user); 
     //if (id == null) 
     //{ 
     // return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
     //} 
     //UserProfile userProfile = db.SelectByID(id); 
     //if (userProfile == null) 
     //{ 
     // return HttpNotFound(); 
     //} 
     //return View(userProfile); 
     } 

模型視圖:

[Table("UserProfile")] 
public class UserProfile 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int UserId { get; set; } 
    public string UserName { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string Email { get; set; } 
    } 

和視圖:

@model ContosoUniversity.Models.UserProfile 
@{ 
    ViewBag.Title = "Edit"; 
} 

<h2>Edit</h2> 

@using (Html.BeginForm("Edit","Account")) 
{ 
    @Html.AntiForgeryToken() 

    <div class="form-horizontal"> 
     <h4>Lola Biker</h4> 
     <hr /> 
     @Html.ValidationSummary(true) 
     @Html.HiddenFor(model => model.UserId) 

     <div class="form-group"> 
      @Html.LabelFor(model => model.LastName, new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.LastName) 
       @Html.ValidationMessageFor(model => model.LastName) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.FirstName, new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.FirstName) 
       @Html.ValidationMessageFor(model => model.FirstName) 
      </div> 
     </div> 

     <div class="form-group"> 
      <div class="col-md-offset-2 col-md-10"> 
       <input type="submit" value="Save" class="btn btn-default" /> 
      </div> 
     </div> 
    </div> 
} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
} 

這是一個asp.net mvc4應用程序,我想編輯firstName d註冊用戶的姓氏。我爲註冊用戶添加了一些額外的屬性。但是,如果我運行的應用程序,我得到這個錯誤:

Object reference not set to an instance of an object. 

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. 

Source Error: 


Line 221:   { 
Line 222: 
Line 223:    UserProfile user = db.SelectByID(id); 
Line 224:    return View(user); 
Line 225:    //if (id == null) 

Source File: g:\Mijn Documents\My Web Sites\Lolabikes\C#\ContosoUniversity\Controllers\AccountController.cs Line: 223 

我登錄,將被重定向到編輯頁面如下:

@if (Request.IsAuthenticated) 
{ 
    <text> 
     Hello, @Html.ActionLink(User.Identity.Name, "Edit", "Account", routeValues: null, htmlAttributes: new { @class = "username", title = "Manage" })! 
     @using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" })) 
     { 
      @Html.AntiForgeryToken() 
      <a href="javascript:document.getElementById('logoutForm').submit()">Log off</a> 
     } 
    </text> 
} 
else 
{ 
    <ul> 
     <li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li> 
     <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> 
    </ul> 
} 

謝謝您的幫助

我ALS試過這樣:

public ActionResult Edit(int? id) 
{ 
    UserProfile user = db.SelectByID(id); 
    return View(user); 
} 

但我仍然得到ID = NULL

我有我的編輯,現在是這樣的:

public ActionResult Edit(int? id) 
{ 
    if (id == null) 
    { 
     return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
    } 
    UserProfile user = db.SelectByID(id); 
    if (user == null) 
    { 
     return HttpNotFound(); 
    } 
    return View(user);    
} 

和看法:

@Html.ActionLink(User.Identity.Name, "Edit", "Account", new { userId = 123 }, new { title = "Manage" }) 

我把斷點這樣的:如果(ID == NULL)

和它說:空= null

我編輯現在是這樣的:

public ActionResult Edit(int?用戶id) {

  //if (userId = null) 
      //{ 
      // return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
      //} 
      UserProfile user = db.SelectByID(userId); 
    //  if (user == null) 
    //  { 
    //   return HttpNotFound(); 
    //  } 
      return View(user);    
     } 

,但用戶是空

所以如果我不喜歡這樣,你有什麼建議:

public ActionResult Edit(int userId) 
{ 
    //your code here you get the userId to manipulate. 
} 

ofcourse我看到那麼空texboxes(名字,姓氏)

好的,我現在是這樣的:

@ Html.ActionL (User.Identity.Name,「Edit」,「Account」,new {Id = Context.User.Identity.Name},new {title =「Manage」})

和一個UserProfile模型,如下所示:

[Table("UserProfile")] 
    public class UserProfile 
    { 

     public int Id { get; set; } 
     public string UserName { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     public string Email { get; set; } 
     //ok 
     public int MyProperty { get; set; } 
    } 

但我的ID是當然一個整數,也在數據庫中。但這:

Id = Context.User.Identity.Name - Identity.Name - 我只看到名稱 - 這是一個字符串,如何改變?

因爲:UserProfile user = db.SelectByID(Id);仍然是用戶是空的?

謝謝

+0

您是否在發送該用戶的ID? – 2014-10-07 11:51:38

+0

你是什麼意思?我已經編輯我的帖子 – 2014-10-07 11:57:44

+0

顯示代碼在哪裏你點擊「編輯」 – 2014-10-07 12:01:53

回答

0

試試這個

@Html.ActionLink(User.Identity.Name, "Edit", "Account", new { userId = *Your ID here* }, new {title = "Manage"}) 

和你的控制器的方法類似

public ActionResult Edit(int userId) 
{ 
    //your code here you get the userId to manipulate. 
} 

你正在做的錯誤是你的路由值提供空。這就是爲什麼你在控制器操作中得到空值的原因。

+0

我試圖說,但問題是我得到一個項目上的錯誤:錯誤當前上下文中不存在名稱'Item'\t g:\ Mijn Documents \ My Web Sites \ Lolabikes \ C# \ ContosoUniversity \ Views \ Shared \ _LoginPartial.cshtml Lolabike – 2014-10-07 12:58:20

+1

此錯誤是因爲您的視圖頁中沒有名爲Item的對象。我想你是MVC的新手。現在除去Item.ID和硬編碼了一些類似'新{用戶id = 123}'和嘗試,電話我發生了什麼 – 2014-10-07 13:03:04

+0

我有編輯自己的帖子 – 2014-10-07 13:08:41

0

好吧,我發現了一個解決辦法,但它是不理想的,因爲我用的是通用存儲庫,但編輯個人資料,我不使用的存儲庫,我這是怎麼固定:

private LolaBikeContext db = new LolaBikeContext(); 



public ActionResult Edit(string UserId) 
      {    

       string username = User.Identity.Name; 

       // Fetch the userprofile 
       UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username)); 

       // Construct the viewmodel 
       UserProfile model = new UserProfile(); 
       model.FirstName = user.FirstName; 
       model.LastName = user.LastName; 
       model.Email = user.Email; 
       model.Motto = user.Motto; 
       model.PlaceOfBirth = user.PlaceOfBirth; 
       model.HowManyBikes = user.HowManyBikes; 
       model.BesideYourBeth = user.BesideYourBeth; 
       model.NicestRide = user.NicestRide; 
       model.WorstRide = user.WorstRide; 
       model.AmountKmPerYear = user.AmountKmPerYear; 
       model.AverageSpeed = user.AverageSpeed; 
       model.AbleToChatWhileRiding = user.AbleToChatWhileRiding; 
       model.PhoneNumber = user.PhoneNumber; 




       return View(user);    
      } 


      [HttpPost] 
      public ActionResult Edit(UserProfile userprofile) 
      { 
       if (ModelState.IsValid) 
       { 
        string username = User.Identity.Name; 
        // Get the userprofile 
        UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username)); 

        // Update fields 
        user.FirstName = userprofile.FirstName; 
        user.LastName = userprofile.LastName; 
        user.Email = userprofile.Email; 
        user.Motto = userprofile.Motto; 

        user.PlaceOfBirth = userprofile.PlaceOfBirth; 
        user.HowManyBikes = userprofile.HowManyBikes; 
        user.BesideYourBeth = userprofile.BesideYourBeth; 
        user.NicestRide = userprofile.NicestRide; 
        user.WorstRide = userprofile.WorstRide; 
        user.AmountKmPerYear = userprofile.AmountKmPerYear; 
        user.AverageSpeed = userprofile.AverageSpeed; 
        user.AbleToChatWhileRiding = userprofile.AbleToChatWhileRiding; 
        user.PhoneNumber = userprofile.PhoneNumber; 

        db.Entry(user).State = EntityState.Modified; 

        db.SaveChanges(); 

        return RedirectToAction("Edit", "Account"); // or whatever 
       } 

       return View(userprofile); 
      } 

所以它不是理想的ofcourse,但現在它的工作原理

+0

在你的第一個ActionResult編輯(GET) - 爲什麼你映射一個UserProfile用戶到另一個UserProfile模型?你對模型沒有做任何事情,所以.. – 2014-10-08 20:26:02

+0

你的意思是? UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username)); – 2014-10-08 21:54:19

+0

我的意思是你的評論下的所有代碼//構建視圖模型 - 不必要,因爲你最終傳遞的是標記爲用戶的對象而不是標記爲模型的對象 – 2014-10-09 02:10:17

0

試試這個

@Html.ActionLink(User.Identity.Name, "Edit", "Account", new { userId = *Your ID here* }, new {title = "Manage"}) 

和你的控制器的方法類似

[HttpPost] 
public ActionResult Edit(int userId = 0) 
{ 
    //your code here you get the userId to manipulate. 
}