【问题标题】:ViewModel instance is null on creatingViewModel 实例在创建时为空
【发布时间】:2015-08-04 01:05:52
【问题描述】:

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

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 的 User 类更改为:

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

我还将创建操作更改为:

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 始终为 Null,我无法获取表单上键入的值。

我猜可能有问题

[Bind(
                    Include =

但我不知道它可能是什么或语法

【问题讨论】:

  • 另请参阅this answer。并从方法中删除无意义的FormCollection formCollection 参数。

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 asp.net-mvc-5


【解决方案1】:

首先我不知道什么是最糟糕的,沿着代码传播的魔法字符串,丑陋的架构或者你基本上将所有 mvc 版本标签添加到问题而不是你正在处理的版本的事实。

那个绑定是一个模型绑定器。

根据模型绑定器的定义 当执行“创建”时,MVC 模型绑定器将使用请求参数来填充用户参数的属性,您应该知道。但是,Bind 属性告诉模型绑定器仅填充具有指定名称的属性。

I beat "Usuario" 总是为空,因为你没有在这个丑陋而巨大的魔法字符串中传递属性

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

【讨论】:

  • 那里使用的语法是什么?
  • [Bind(Include = "Usuario,UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department" 试试那个
  • 最好的办法是根本不用它。 Bind 是微软投入 MVC 的另一个混蛋,它本来就不应该存在。它不是强类型的,因为从本质上讲,它由一串属性名称组成,没有验证它们是否正确。使用视图模型的全部意义在于只实现用户应该能够触摸的属性。因此,Bind 和使用视图模型是相互排斥的方法。
  • 我完全同意你的评论,我只是回答这个问题,但我从一开始就说这个解决方案很糟糕。模型活页夹是一个非常强大的工具,但不是这样使用的。有时你真的有例如,如果您使用 DI 创建上下文来绑定某些东西,但在这种情况下,您可以构建一个真正的模型绑定器,而不使用 bind with 涉及硬编码字符串,通常意味着 crappie 代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-17
  • 2019-03-13
  • 2021-11-28
相关资源
最近更新 更多