Использование AspNetUsers.Id в форме - PullRequest
0 голосов
/ 26 февраля 2019

Я хочу, чтобы человек зарегистрировался (используя существующую страницу регистрации), а затем был направлен в форму, где его AspNetUsers.Id = UserId (на моей странице CreateProfile).CreateProfile - это страница, на которую вы направляетесь после успешной регистрации.Как вы можете видеть на изображении в адресной строке, вы можете видеть идентификатор пользователя, но он не появится в поле ввода.

AccountController

public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    // Registered user is given the applicant role by default
                    UserManager.AddToRole(user.Id, "Applicant");

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                    ViewBag.UserId = user.Id;
                    //return RedirectToAction("Index", "Home");
                    return RedirectToAction("CreateProfile", new { controller = "Admin", UserId = user.Id });
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

CreateProfile View

@model NAA.Data.Profile

@{
    ViewBag.Title = "CreateProfile";
}

<h2>Create Profile</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Profile</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.ApplicantName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ApplicantName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ApplicantName, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

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

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

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

<div>
    @Html.ActionLink("Back to List", "GetProfile", new { controller = "Profile", action = "GetProfile" })
</div>

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

Изображение CreateProfile
Действие контроллера

1 Ответ

0 голосов
/ 28 февраля 2019

у вас есть две основные проблемы:

  1. В действии Register вы передаете значение userId с помощью ViewBag, а затем используете RedirectToAction.Вы не можете использовать ViewBag для этого сценария, потому что значение будет потеряно. Проверьте здесь

  2. Вы не назначаете значение UserId в поле ввода [представление CreateProfile].

Чтобы решить это:

Записать значение UserId в CreateProfile Get Action, а затем назначить в ViewBag для передачи значения в View.Две формы:

а.Используйте MVC bind, установите переменную:

// Get: Admin/CreateProfile
public ActionResult CreateProfile(string UserId) // <== here
{
    ViewBag.UserId = UserId;
    return View();
}

b.Используйте объект запроса для получения значения.

// Get: Admin/CreateProfile
public ActionResult CreateProfile()
{
    ViewBag.UserId = Request.Params["UserId"]; // <== here
    return View();
}

Необязательно : вы можете сохранить значение UserId, используя объект сеанса в действии регистра.Может быть, я хотел бы этого, потому что избегать до кода. Проверьте здесь .

Наконец, присвойте значение UserId в поле ввода в представлении CreateProfile, используя @Value:

new {htmlAttributes = new {@class = "form-control", @ Value =ViewBag.UserId }

IE:

<div class="form-group">
    @Html.LabelFor(model => model.UserId, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.UserId, new { htmlAttributes = new { @class = "form-control", @Value= ViewBag.UserId } })
        @Html.ValidationMessageFor(model => model.UserId, "", new { @class = "text-danger" })
    </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...