在创建视图中,我想要做的是从下拉列表中选择一个名称,以自动填充Login html.TextBoxFor及其详细信息。
目前,当我从下拉列表中选择一个人时,登录文本框仍为空。
所以我得到了我的json对象并测试了我的sql,这很好,所以我想问题必须在jquery的某个地方。
如果你能帮我找到错误,我会很高兴。
查看:
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
<div class="editor-label">@Html.LabelFor(model => model.UserLogin)</div>
<div class="editor-field">@Html.TextBoxFor(model => model.UserLogin, new {id ="LoginId" })
@Html.ValidationMessageFor(model => model.UserLogin)</div>
<div class="editor-label">@Html.LabelFor(model => model.UserFullName)</div>
<div class="editor-field">@Html.DropDownList("UserFullName", ViewBag.UserFullName as SelectList, "Select a User", new { id = "UserID" })
@Html.ValidationMessageFor(model => model.UserFullName)</div>
<p>
<input type="submit"
value="Create" />
</p>
</fieldset> }
<div>@Html.ActionLink("Back to List", "Index")</div>
<script type="text/javascript">
$('#UserID').on('change', function () {
$.ajax({
type: 'POST',
url: '@Url.Action("GetUserForm")',
data: { FullName: $('#UserID').val() },
success: function (results){
var login = $('#LoginId');
login.empty();
$.each(results, function ()
{
login.val(this.ID).text(this.Value);
});
}});
});
</script>
控制器:
public ActionResult Create()
{
var names = StaffDB.StaffData.AsEnumerable().Select(s => new
{
ID = s.ID,
FullName = string.Format("{0} {1}", s.Forename1, s.Surname)
}).ToList();
if(ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserFullName = new SelectList(names, "FullName", "FullName", user.UserFullName);
return View(user);
}
[HttpPost]
public JsonResult GetUserForm(string FullName)
{
//pseudo code
var data = from s in StaffDB.StaffData
where s.Forename1 + ' ' + s.Surname == FullName
select new
{
Value = s.Login,
ID = s.ID
};
return Json(data);
}
答案 0 :(得分:0)
我认为问题是在返回json时,默认情况下在MVC中Jsonresult是“Deny get”,所以你添加了“Allow Get”。
[HttpPost]
public JsonResult GetUserForm(string FullName)
{
//pseudo code
var data = from s in StaffDB.StaffData
where s.Forename1 + ' ' + s.Surname == FullName
select new { Value = s.Login, ID = s.ID };
if (data == null)
return Json(null);
return Json(data , JsonRequestBehavior.AllowGet);
}