0

Edit同じアクションで挿入と更新を行うコントローラーがあります。そこで、 に対してチェックを行いActive Directoryます。ユーザーが入力して再確認したユーザー名が一致しないために挿入が失敗した場合、アプリケーションは検証エラーを表示する必要がありますActive Directory。アクションで複数のエントリが発生するため、後のユーザー名が有効であっても、その特定のユーザーの挿入を停止する必要があります。

問題:私のコードは現在 ModelState チェックを使用していますが、検証メッセージを VIEW に渡すことはできません。この場合、モデルは実際には状態を変更していないためです。

質問:特定のモデル プロパティ (この場合はユーザー名) を DB に挿入する前に、サーバー側のチェックを行うにはどうすればよいですか?

仮定:ユーザー名チェック メソッドはユーザー名自体を返し、それをビューに渡してエラー メッセージを表示する必要がありますか?

制限:必須フィールドではないためAnnotation、モデルで を使用できませんでした。IsRequiredユーザー名テキスト ボックスが空の場合でも、ユーザーはユーザーの現在のリストを編集して保存できる必要があります。ユーザー名がテキスト ボックスに入力されて挿入が行われた場合にのみ、検証が必要です。Active Directory重いので、クライアント側のチェックはできません。これはファイルされた検証ではなく、悪いデータが DB に到達しないことを確認します。

モデル:

public class User
{
    [Key]
    public string username { get; set; } 

    [Key]
    public string role { get; set; }

}

意見:

@model List<Project.ViewModels.UserViewModel>
@using (@Html.BeginForm())
{
<table class="table">
    <tr>
        <th>User</th>
        @for (int i = 0; i < Model[0].Roles.Count; i++)
        {
            <th>
                @Model[0].Roles[i].RoleName
            </th>
        }
    </tr>
    @for (int i = 0; i < Model.Count; i++)
    {
        <tr>
            <td>                
                @if (Model[i].UserName == null)
                {
                    @Html.EditorFor(m=> m[i].UserName)
                    @Html.ValidationMessageFor(m=> m[i].UserName)
                    if (!ViewData.ModelState.IsValid)
                    {
                        <span class="field-validation-error">
                            @ViewData.ModelState["UserName"].Errors[0].ErrorMessage
                        </span>
                    }
                }
                else
                {
                    @Html.HiddenFor(m => m[i].UserName)
                    @Model[i].UserName
                }
            </td>
            @for (int j = 0; j < Model[i].Roles.Count; j++)
            {
                <td>
                    @Html.HiddenFor(m => m[i].Roles[j].RoleName)
                    @Html.CheckBoxFor(m => m[i].Roles[j].IsSelected)
                </td>
            }
        </tr>
    }    
</table>

<div class="form-actions">
    <button id="SubmitUserRoles" type="submit" class="btn btn-success submit" value="Save">Save</button>
</div>
}

<script>
    $("#SubmitUserRoles").click(function () {
        $.ajax({
            url: '@Url.Action("Edit", "Users")',
            type: 'POST',
            cache: false,
            data: JSON.stringify($('form').serialize()),
            success: function (data) {
                window.location.href = data
            }, error: function (xhr, ajaxOptions, error) {
                console.log(xhr.status);
                console.log("Error: " + xhr.responseText);
            }
        });
    });
});

コントローラ:

[HttpPost]
    public ActionResult Edit(List<UserViewModel> model)
    {
        var level = model[0].Level;
        var location = model[0].Location;

        for (int i = 0; i < model.Count; i++)
        {
            if (model[i].UserName != null)
            {
                var uName = model[i].UserName;
                for (int j = 0; j < model[i].Roles.Count; j++)
                {

                    var uRole = model[i].Roles[j].RoleName;
                    var uRoleSelected = model[i].Roles[j].IsSelected;

                    var userWithSpecificRole = db.Users.FirstOrDefault(m => m.username == uName && m.role == uRole);

                    if (uRoleSelected && userWithSpecificRole == null)
                    {
                        if (DoesUserExist(uName))
                        {
                            if (ModelState.IsValid) 
                            { 
                                db.Users.Add(new User
                                {
                                   username = uName,
                                   role = uRole,
                                });                             
                                db.SaveChanges();
                            }
                        }
                        else
                            ModelState.AddModelError("UserName", "Username does not exist!");
                    }
                }
            }
        }
        return Json(Url.Action("Index", "Users", new {level,location}));
    }

ユーザー名をチェックする方法Active Directoryは次のとおりです。

    private bool DoesUserExist(string username)
    {
        PrincipalContext domain = new PrincipalContext(ContextType.Domain, "CompanyDomain", "DC=CompanyDomain,dc=com");

        UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, username);

        return foundUser != null;
    }
4

0 に答える 0