对象参考,无法找到用户ID

时间:2016-02-02 14:39:42

标签: c# mysql asp.net-mvc authentication model-view-controller

在我的项目中,我试图将用户能力从仅能够“编辑”地址字段变为能够“创建”和“编辑”(如果它已存在于同一视图中)。我收到以下服务器错误Click Here

然后我通过调试器运行它并收到以下结果Click Here Too!我可以看到我的用户ID在控制器中作为null传递,从而产生服务器错误。但在遵循Pratt先生的建议之后,我可以看到用户ID被传递到视图中我不确定为什么会发生这种情况或者我犯了错误。

控制器

// GET: /UserProfile/Edit/5
public ActionResult Edit(int id)
{
    var userProfile = db.UserProfiles.FirstOrDefault(up => up.UserId == id);
    var query = from o in db.UserProfiles
                where o.Address != null
                select o;
    ViewBag.Query = query;
    // if the user is not an admin
    if (!User.IsInRole("admin"))
    {
        // look up current user id
        var currentUserId = (int)System.Web.Security.Membership.GetUser().ProviderUserKey;

        // check to make sure that the user profile is attached to the currently logged in user
        if (userProfile.UserId == currentUserId)
        {
            return View(userProfile);
        }
        else
        {
            throw new Exception("you cannot access a user profile that is not your own");
        }
    }

    // the user is an admin, so let them view the profile
    return View(userProfile);
}

查看

@model YardLad.Models.Domain.UserProfile

@{
    ViewBag.Title = "Edit Profile";
}

<h2>Edit Profile</h2>

@if (User.IsInRole("contractor") || User.IsInRole("contractor2"))
{
<style>
    #content a {
        color: cornflowerblue;
    }

    #content a:hover {
        color: cornflowerblue;
    }
    </style>
}

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"     type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

@Html.HiddenFor(m => m.UserId)
@Html.HiddenFor(m => m.AcceptSMS)
@Html.HiddenFor(m => m.IsActive)
@Html.HiddenFor(m => m.LastLoginDate)

@Html.HiddenFor(m => m.AddressId)

<div class="editor-label">
    Name
</div>
<div class="editor-field">
    @Html.EditorFor(m => m.FirstName)
    @Html.ValidationMessageFor(m => m.FirstName)
</div>

<div class="editor-field">
    @Html.EditorFor(m => m.LastName)
    @Html.ValidationMessageFor(m => m.LastName)
</div>

<div class="editor-label">
    @Html.LabelFor(m => m.Phone)
</div>
<div class="editor-field">
    @Html.TextBoxFor(m => m.Phone)
    @Html.ValidationMessageFor(m => m.Phone)
</div>

<div class="editor-label">
    @Html.LabelFor(m => m.Mobile)
</div>
<div class="editor-field">
    @Html.TextBoxFor(m => m.Mobile)
    @Html.ValidationMessageFor(m => m.Mobile)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.DateOfBirth)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.DateOfBirth)
    @Html.ValidationMessageFor(model => model.DateOfBirth)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
    @Html.RadioButton("Gender", "male") male
    @Html.RadioButton("Gender", "female") female
    @Html.ValidationMessageFor(m => m.Gender)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.AddressId, "Address")
</div>

var address = ViewContext.ViewData.ModelState["Address"];

if (address != null && address.Errors.Count() > 0)
{
    @Html.ActionLink("Add a billing address", "Create", "Address",
    new { returnUrl = "UserProfile/Edit", userId = Model.UserId }, null)
}
else
{
    <div class="editor-field">
        @Html.DisplayFor(m => m.Address.Line1)<br />
        @*@if (Model.Address.Line2 != null && address.Any())
        {
            @Html.DisplayFor(m => m.Address.Line2)<br />
        }*@
        @Html.DisplayFor(m => m.Address.City), @Html.DisplayFor(m => m.Address.State.Abbreviation) @Html.DisplayFor(m => m.Address.PostalCode)
    </div>
    if (ViewBag.Query != null || ViewBag.Query != "" )
    {
       @Html.ActionLink("Add an address", "Create", "Address", new { id = Model.AddressId, returnUrl = "UserProfile/Edit", userId = Model.UserId }, null)
    }
    else
    {
        @Html.ActionLink("Edit address", "Create", "Address", new { id = Model.AddressId, returnUrl = "UserProfile/Edit", userId = Model.UserId }, null)
    }
}

@*<div class="editor-field">
    <span>@Html.CheckBoxFor(m => m.AcceptSMS)</span>
    <span class="editor-label">
        @Html.LabelFor(m => m.AcceptSMS, "Accept SMS Service")
    </span>
    <p style="width: 50%; min-width: 300px;">
        this free service allows you to send and receive text updates for easier access to making payments, scheduling reoccurring services, rating services, etc.<br />
        <span style="font-size: .9em; color: forestgreen;">standard SMS charges still apply (based on your mobile carrier and plan)</span>
    </p>
</div>*@

<p>
    <input type="submit" value="Save" />
</p>
}

<div>
@Html.ActionLink("Back to My Account", "MyAccount", "Account")
</div>

1 个答案:

答案 0 :(得分:0)

userProfile为空。您需要进行适当的空值检查:

var userProfile = db.UserProfiles.FirstOrDefault(up => up.UserId == id);
if (userProfile == null)
{
    return new HttpNotFoundResult();
}