你可以说我是C#MVC的新手,遇到了一些问题,经常研究,这是我的第一个话题。
我正在开发一个使用活动目录数据的应用程序。我有一个用户从AD导入数据。 这是我的控制器创建代码:
[HttpPost]
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
DirectorySearcher directorySearch = new DirectorySearcher();
directorySearch.Filter = "(&(objectClass=user)(SAMAccountName=" + user.IdUser + "))";
SearchResult results = directorySearch.FindOne();
if (results != null)
{
if (results.Properties.Contains("mail")) //E-mail
{
user.E_mail = results.Properties["mail"][0].ToString();
}
else
{
user.E_mail = string.Empty;
}
if (results.Properties.Contains("c")) //Country
{
user.Country = results.Properties["c"][0].ToString();
}
else
{
user.Country = string.Empty;
}
}
db.User.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CompanyCode = new SelectList(db.Company, "CompanyCode", "CompanyName", user.CompanyCode);
ViewBag.Country = new SelectList(db.Country, "CountryName", "CountryName", user.Country);
return View(user);
}`
这是我的一些创建视图代码:
<div class="editor-label">
@Html.LabelFor(model => model.IdUser)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.IdUser)
@Html.ValidationMessageFor(model => model.IdUser)
我想要做的是检查AD是否用户确实存在函数并将值返回到IdUser字段但是在点击提交之前,就像检查名称一样。
我想到的解决方案, 在视图中只需按一下按钮:
<p>
<input type="submit" value="Check" onClick="CheckFunction(model.IdUser)" />
</p>
,功能类似于:
public string CheckFunction(string Id)
{
DirectorySearcher directorySearch = new DirectorySearcher();
directorySearch.Filter = "(&(objectClass=user)(SAMAccountName=" + Id + "))";
SearchResult results = directorySearch.FindOne();
if (results != null)
{
return Id;
}
return string.Empty;
}
但问题是我不知道如何将Function中返回的Id字符串设置为model.IdUser字段。
你们能帮助我吗?
答案 0 :(得分:0)
你需要在你的按钮上放一个类(class =“btnSave”代码如下)
$('.btnSave').on('click', function(e){
$.ajax({
url: '@(Url.Action("CheckFunction", "Controller"))',
type: 'post',
data: {
//this is the id that is passed. change @Model.Id to whatever id you want sent
Id: '@Model.Id'
},
success: function (result) {
if(result.Success){
//if this is a submit button it will do a post back. If just a button you can set fields with the returned data or alert, etc
$('.fieldId').val(result.Id);
}else{
//e.preventDefault() will stop the submit button from submitting if failed is returned
e.preventDefault();
//do something for failure (alert or something)
}
}
});
});
然后更改您的控制器以返回json成功或失败。这是json success and fail response in MVC
的示例