简体   繁体   English

编辑userPropfile asp.net mvc4

[英]Edit userPropfile asp.net mvc4

I have this: 我有这个:

Controller action: 控制器动作:

 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);
      }

ModelView: 模型视图:

 [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; }
  }

And the view: 和视图:

@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")
}

It is an asp.net mvc4 application and I want to edit the firstName and LastName of the registered user. 这是一个asp.net mvc4应用程序,我要编辑注册用户的名字和姓氏。 I add some extra properties to the Register user. 我向“注册”用户添加了一些额外的属性。 But If I run the application I get this error: 但是,如果我运行该应用程序,则会出现此错误:

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 

I am logged in and will be redirected to the edit page like this: 我已经登录,将被重定向到编辑页面,如下所示:

@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>
}

Thank you for your help 谢谢您的帮助

I als tried like this: 我也尝试过这样:

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

but then I still get id = null 但是我仍然得到id = null

I have my Edit now like this: 我现在有这样的编辑:

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);               
}

and view: 并查看:

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

I put breakpoint on this: if (id == null) 我对此设置了断点:if(id == null)

and it says: null = null 它说:null = null

I have the Edit now like this: 我现在有这样的编辑:

public ActionResult Edit(int? userId) { public ActionResult Edit(int?userId){

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

but user is null 但用户为空

so If I do it like this , what you suggest: 因此,如果我这样做,您的建议是:

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

ofcourse I see then empty texboxes(firstName, lastName) 当然我看到然后是空的texboxes(firstName,lastName)

ok, I have it now like this: 好的,我现在是这样的:

@Html.ActionLink(User.Identity.Name, "Edit", "Account", new { Id= Context.User.Identity.Name }, new { title = "Manage" }) @ Html.ActionLink(User.Identity.Name,“编辑”,“帐户”,新的{Id = Context.User.Identity.Name},新的{title =“ Manage”})

and a model UserProfile, like this: 和模型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; }
    }

But my Id is ofcourse a integer, also in the datbase. 但是我的Id当然也是一个整数,也在datbase中。 but this: 但是这个:

Id= Context.User.Identity.Name - Identity.Name - I only see Name - that is a string, how to change that?? id = Context.User.Identity.Name-Identity.Name-我只看到Name-这是一个字符串,如何更改?

because: UserProfile user = db.SelectByID(Id); 因为:UserProfile用户= db.SelectByID(Id); still user is null???? 仍然用户为空吗?

Thank you 谢谢

Try this 尝试这个

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

and your controller method like 和你的控制器方法像

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

the mistake you are doing is you are providing null for the route values. 您所做的错误是您为路由值提供了空值。 Which is why you are getting null in your controller action. 这就是为什么您在控制器操作中得到null的原因。

ok, I found a workaround, but it is not ideal, because I am using a Generic repository, but for edit profile, I dont use the repository, this is how I fixed: 好的,我找到了一种解决方法,但这并不理想,因为我使用的是通用存储库,但是对于编辑配置文件,我不使用存储库,这是我固定的方法:

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);
            }

So it is not ideal ofcourse , but for now it works 因此,这不是理想的课程,但目前可以正常工作

Try this 尝试这个

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

and your controller method like 和你的控制器方法像

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM