在.net中使用默认表单填充值

本文关键字:表单 填充 默认 net | 更新日期: 2023-09-27 18:15:44

我有一个IdentityUser模型

我有一个管理视图与3部分(每一个有一个视图模型和控制器),我想在这个视图上输入,并看到与模型的数据填充的表单。

ApplicationUser: IdentityUser (Model of my user)

using Microsoft.AspNet.Identity.EntityFramework;
using System;
namespace MTGWeb.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
        public String Pais;
        public String Email;
        public DateTime UltimoLogin;
        public DateTime FechaRegistro;
        public String Tipo;
        public Boolean Activado;
    }
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }
}

Manage (Main View)

@using MTGWeb.Models;
@using Microsoft.AspNet.Identity;
@{
    ViewBag.Title = "Administrar cuenta";
}
<h2>@ViewBag.Title.</h2>
<p class="text-success">@ViewBag.StatusMessage</p>
<div class="row">
    <div class="col-md-12">
        <p>Ha iniciado sesión como <strong>@User.Identity.GetUserName()</strong>.</p>
        @Html.Partial("_ChangePasswordPartial")
        @Html.Partial("_ChangeEmailPartial")
        @Html.Partial("_OtherFieldsPartial")
    </div>
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

_ChangeEmailPartial

@using Microsoft.AspNet.Identity
@model MTGWeb.Models.ManageUserViewModelEmailChange
@using (Html.BeginForm("ManageEmail", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Formulario para cambiar email</h4>
    <hr />
    @Html.ValidationSummary()
    <div class="form-group">
        @Html.LabelFor(m => m.OldEmail, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.OldEmail, new { @class = "form-control", Value = Model.OldEmail})
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.NewEmail, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.NewEmail, new { @class = "form-control" }) 
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmEmail, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.ConfirmEmail, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Cambiar email" class="btn btn-default" />
        </div>
    </div>
}

Controller - ManageEmail

// Cambia el email
// POST: /Account/ManageEmail
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ManageEmail(ManageUserViewModelEmailChange model)
{
    ViewBag.ReturnUrl = Url.Action("Manage");

    var user = await UserManager.FindByNameAsync(User.Identity.Name);
    if (ModelState.IsValid)//Si no hay errores en la validación que hace la clase (Datatype, length, required, etc..)
    {
        if (model.OldEmail.Equals(model.NewEmail) && model.OldEmail.Equals(user.Email))
        {
            user.Email = model.NewEmail;
            IdentityResult success = await UserManager.UpdateAsync(user);
            if (success.Succeeded)
            {
                return RedirectToAction("Manage", new { Message = ManageMessageId.ChangeEmailSuccess });
            }
        }
    }
    //Si el modelo no es válido o no el cambio no ha tenido exito
    return View(model);
}

对于其他部分,我还有2个控制器,但这对于示例很有用。这些Model.OldEmail是空的,导致Nullreference错误,我要在哪里填充它?我猜这个必须填入AccountController/Manage,但是…我怎么把它放到偏导数里呢?

我是MVC和。net的新手,我曾经使用Java工作,我被困在这个(是一个测试项目的目的)

在.net中使用默认表单填充值

将您希望局部显示的模型作为参数传递给局部您将需要添加一个视图模型,其中包含您想要显示给主机视图的模型。

  @Html.Partial("_ChangePasswordPartial",Model.ChangePAsswordViewModel)

Model是控制器的一个属性(你的管理控制器将从它继承)

您通过您的manage controller方法将视图模型从return View(YourViewModelInstance)中的控制器传递到管理视图。

您还需要在您的管理表单中添加对该模型的引用,就像您在partials中所做的那样如

 @model MTGWeb.Models.ManageViewModel

您的管理视图模型可能看起来像

public class ManageViewModel
{
    public ChangePasswordViewModel ChangePasswordViewModel{get;set;}
    public NextViewModel NextViewModel{get;set;}
    public AnotherViewModel NextViewModel{get;set;}
}