在.NET中默认填充值

时间:2014-07-30 15:07:44

标签: c# asp.net-mvc

我有一个IdentityUser模型

我有一个带有3个局部视图的管理视图(每个部分有一个视图模型和控制器)我想在此视图中输入并查看模型填充数据的表单。

ApplicationUser:IdentityUser(我的用户的型号)

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

管理(主视图)

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

控制器 - 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,我被困在这里(是一个测试项目目的)

1 个答案:

答案 0 :(得分:1)

将您希望部分显示的模型作为参数传递给partials 您需要添加一个包含要显示的模型的视图模型到主机视图。

例如

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

Model是Controller上的一个属性(管理控制器将从中继承)

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

您还需要在管理表单中添加对该模型的引用,就像您在部分中一样 例如

 @model MTGWeb.Models.ManageViewModel

您的管理视图模型可能类似于

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