视图模型实例创建空 [英] ViewModel instance is null on creating

查看:110
本文介绍了视图模型实例创建空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创造了这个视图模型类:

I created this view model class:

using System.Collections.Generic;
using Microsoft.Azure.ActiveDirectory.GraphClient;

namespace xx.Models.GlobalAdmin.Models
{
    public class UserViewModel
    {
        public  User Usuario { get; set; }
        public List<string> SelectedCompanies { get; set; }
    }
}

和我改变了我的Create.cshtml从Active Directory的用户类这样的:

and I changed my Create.cshtml from the User class from Active directory to this:

@model CapatechSaasApp.Models.GlobalAdmin.Models.UserViewModel

和所有像这样的控件:

<div class="form-group">
    @Html.Label("Usuario", new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <div class="input-group">
            @Html.EditorFor(model => model.Usuario.UserPrincipalName)
            <span class="input-group-addon" id="basic-addon2">@SettingsHelper.Domain.ToString()</span>
            @Html.Validatiomodel => model.Usuario.UserPrincipalName)
        </div>
    </div>
</div>

我也改变了创建行动,以这样的:

I also changed the Create action to this:

public async Task<ActionResult> Create(
    [Bind(Include = "UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department"
                )] CapatechSaasApp.Models.GlobalAdmin.Models.UserViewModel user, FormCollection formCollection)
        {
            ActiveDirectoryClient client;
            try
            {
                client = AuthenticationHelper.GetActiveDirectoryClient();
            }
            catch (Exception)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext()
                        .Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return View();
            }

            try
            {
                var usuario = user.Usuario.UserPrincipalName;
                user.Usuario.UserPrincipalName = usuario+SettingsHelper.Domain;
                user.Usuario.MailNickname = usuario;
                user.Usuario.AccountEnabled = true;
                await client.Users.AddUserAsync(user.Usuario);

                //Setting extended property lookup name
                var extPropLookupName = $"extension_{SettingsHelper.ClientId.Replace("-", "")}_{"Compania"}";

                //TO BE FINISHED
                user.Usuario.SetExtendedProperty(extPropLookupName, formCollection["Empresa"]);
                await user.Usuario.UpdateAsync();
                //Task.WaitAll();

                // Save the extended property value to Azure AD.
                user.Usuario.GetContext().SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return View();
            }
        }

不过user.Usuario总是空,我不能让输入表单上的值。

However user.Usuario is always Null and I cant get the values typed on the form.

我想可能有什么问题。

[Bind(
                    Include =

但我不知道会不会是或语法

But I dont know what could it be or the syntax

推荐答案

所有我不知道什么是最糟糕的,沿code魔术字符串s $ P $垫,丑建筑或事实上的第一那你基本上添加的所有MVC版本标签的问题,而不是你正在使用的版本。

First of all I don't know what is worst, the magic string spread along the code, the ugly architecture or the fact that you basically add all mvc version tags to the question instead of the version you are working on.

这是绑定模型粘合剂。

通过模型绑定的定义
当创建执行MVC模式的粘合剂将使用请求参数填充用户参数的属性,因为你应该知道。但是,绑定属性告诉模型绑定只填充指定的名称属性。

By the definition of Model Binder When "Create" is executed the MVC model binder will use the request parameters to populate the user parameter's properties, as you should know. However, the Bind attribute tells the model binder to only populate properties with names specified.

我拍Usuario总是空,因为你不及格的财产在这个丑陋和魔幻巨串

I beat "Usuario" is always null because you are not passing the property in this ugly and giant magic string

[Bind(Include = "UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department"

这篇关于视图模型实例创建空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆