简体   繁体   English

如何获取登录用户的用户名并进行比较以获取ID

[英]How to get the username of a logged in user and compare it to get the id

I want to be able to get the username of the logged in user in my C# ASP.net application so I can get the ID of that user. 我希望能够在C#ASP.net应用程序中获取登录用户的用户名,以便获取该用户的ID。 I then want to perform an edit so they can apply to be part of an appointment. 然后,我想进行编辑,以便他们可以申请成为约会的一部分。

With my current code, I click the link and I just get a HTTP 400 error. 使用当前代码,单击链接,我仅收到HTTP 400错误。 I have debugged this and the ID is coming through as the correct value. 我已对此进行调试,并且ID已作为正确值通过。 Is there any reason that its not being attached to the url? 是否有任何原因未将其附加到URL?

// GET: 
    public ActionResult VolunteerCeremony(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        string userName = string.Empty;

        //if (System.Web.HttpContext.Current != null &&
        //    System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
        //{
        //    System.Web.Security.MembershipUser usr = System.Web.Security.Membership.GetUser();
        //    if (usr != null)
        //    {
        //        userName = usr.UserName;
        //    }
        //}

        var getVolunteerId = (from u in db.Volunteers
                              where WebSecurity.CurrentUserName == u.Username
                              select u.VolunteerId).FirstOrDefault();


        Volunteer volunteer = db.Volunteers
            .Include(p => p.Appointments)
            .Where(i => getVolunteerId == id)
            .FirstOrDefault();

        if (volunteer == null)
        {
            return HttpNotFound();
        }
        PopulateAssignedCeremonyData(volunteer);
        return View(volunteer);
    }

    // POST: /Player/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult VolunteerCeremony(int? id, string[] selectedOptions)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        var getVolunteerId = (from u in db.Volunteers
                              where WebSecurity.CurrentUserName == u.Username
                              select u.VolunteerId).FirstOrDefault();


        var updateVolunteerWithCeremony = db.Volunteers
            .Include(p => p.Appointments)
            .Where(i => getVolunteerId == id)
            .Single();

        try
        {
            UpdateVolunteerCeremonies(selectedOptions, updateVolunteerWithCeremony);

            db.Entry(updateVolunteerWithCeremony).State = EntityState.Modified;
            db.SaveChanges();

            return RedirectToAction("Index");
        }
        catch (RetryLimitExceededException /* dex */)
        {
            //Log the error (uncomment dex variable name and add a line here to write a log.
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
        }


        PopulateAssignedCeremonyData(updateVolunteerWithCeremony);
        return View(updateVolunteerWithCeremony);
    }

EDIT This is where I'm calling the method 编辑这是我在调用方法的地方

else if(Request.IsAuthenticated && HttpContext.Current.User.IsInRole("Volunteer"))
                    {
                        <li>@Html.ActionLink("Appointments", "Create", "Appointments")</li>
                        <li>@Html.ActionLink("Join Ceremony", "VolunteerCeremony", "Volunteers")</li>
                    }

EDIT 2 Here's my ViewModel that I used for the many to many relationship I have: 编辑2这是我用于多对多关系的ViewModel:

public class VolunteerCeremonyVM
{
    public int AppointmentId { get; set; }
    public string DetailsOfAppointment { get; set; }
    public bool Assigned { get; set; }

    public VolunteerCeremonyVM()
    {
        this.AppointmentId = AppointmentId;
        this.DetailsOfAppointment = DetailsOfAppointment;
        this.Assigned = Assigned;
    }

}

Based on further clarification, you will want to update your ViewModel to include a VolunteerId . 根据进一步的说明,您将需要更新ViewModel以包含VolunteerId So it should look something like: 所以它应该看起来像:

public class VolunteerCeremonyVM
{
    public int AppointmentId { get; set; }
    public string DetailsOfAppointment { get; set; }
    public bool Assigned { get; set; }
    public int VolunteerId { get; set; }
}

Notice that I removed the default constructor as it wasn't doing anything. 注意,我删除了默认构造函数,因为它没有执行任何操作。 When you construct the object you can use code like the following: 构造对象时,可以使用如下代码:

var model = new VolunteerCeremonyVM {
    AppointmentId = 10,
    VolunteerId = 50,
    //etc
};

As this will set all of the properties after the basic object is constructed. 因为这将在构造基本对象之后设置所有属性。

Then, you will want to pass this view model into the view that is generating your action links like so: return View(model); 然后,您将需要将此视图模型传递到生成操作链接的视图中,如下所示: return View(model); in whatever controller action you're using. 无论您使用哪种控制器操作。

Inside the view, you will make use of this new information. 在视图内部,您将利用此新信息。 Specifically, the Html.ActionLink method requires that any extra parameters are passed to it in a route dictionary. 具体来说, Html.ActionLink方法要求在路由字典中将任何其他参数传递给它。 It uses this route dictionary to build the URL that is generated for the anchor tag. 它使用此路由字典来构建为锚标记生成的URL。 You can call Html.ActionLink with an anonymous object for its fourth parameter to specify the route dictionary. 您可以使用匿名对象的第四个参数调用Html.ActionLink ,以指定路由字典。 The id will be the name of the parameter and Model.VolunteerId will be the value of the current volunteer. id将是参数的名称,而Model.VolunteerId将是当前志愿者的值。

Change the Html.ActionLink call to the following to pass an id: Html.ActionLink调用更改为以下代码以传递ID:

@Html.ActionLink("Join Ceremony",
    "VolunteerCeremony",
    "Volunteers",
    new { id = Model.VolunteerId },
    null)

This should fill in the id parameter of the ActionLink with the currently logged in user's userId which should generate the following link: /Volunteers/VolunteerCeremony/3 or whatever the ID actually is. 这应该使用当前登录的用户的userId填充ActionLink的id参数,该用户ID会生成以下链接: /Volunteers/VolunteerCeremony/3或任何实际的ID。

For the form side, you will also need a hidden field on the form so the correct id is sent along with the request. 对于表单,在表单上还需要一个隐藏字段,以便正确的ID与请求一起发送。 You will need to add a VolunteerId to the form ViewModel that you create when generating the form page. 您将需要在生成表单页面时将VolunteerId添加到您创建的表单ViewModel中。 Once you've done that, inside the form itself, you will need to add the following: 完成此操作后,您将需要在表单内部添加以下内容:

Html.Hidden("id", Model.VolunteerId)

This creates an <input type="hidden" name="id" value="3" /> tag that will be sent with the form on post back to the server. 这将创建一个<input type="hidden" name="id" value="3" />标记,该标记将与表单一起发送回服务器。 Since the tag's name is id this will match with the id that's defined in your controller action. 由于标签的名称是id因此它将与您在控制器操作中定义的id相匹配。

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

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