ViewModel实例在创建时为空
本文关键字:创建 实例 ViewModel | 更新日期: 2023-09-27 18:06:12
我创建了这个视图模型类:
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。从Active directory的User类中删除cshtml:
@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();
}
}
然而用户。通常总是Null,我无法获得表单上键入的值。
我猜可能有问题
[Bind(
Include =
但是我不知道它是什么或者语法
首先,我不知道什么是最糟糕的,神奇的字符串沿着代码蔓延,丑陋的架构或事实,你基本上添加所有mvc版本标签的问题,而不是你正在研究的版本。
该绑定是一个Model绑定。
根据Model Binder的定义当"Create"被执行时,MVC模型绑定器将使用请求参数来填充用户参数的属性,你应该知道。然而,Bind属性告诉模型绑定器只使用指定的名称填充属性。
我打败了"Usuario"总是null因为你没有在这个丑陋而巨大的魔法字符串
中传递属性[Bind(Include = "UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department"