【发布时间】:2019-04-28 20:55:25
【问题描述】:
在使用 mvc 应用程序时,我在 jQuery 中遇到了这种奇怪的行为。
下面是 MVC 视图,我在其中实现了文本更改事件,
@Html.TextBoxFor(m => m.UserId, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.UserId, "", new { @class = "text-danger" })
$("#UserId").change(function () {
var UserId = $(this).val();
//$("#txtName").val(emailId);
$.ajax({
url: 'GetValidUserName',
type: 'POST',
data: JSON.stringify({ UserId: UserId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
if (!$.trim(data)) {
alert("User does not exist in system. Please enter valid User Id.");
$(':input[type="submit"]').prop('disabled', true);
}
else {
$("#UserId").val(data);
$("#UserId").focus();
$(':input[type="submit"]').prop('disabled', false);
}
}
});
});
当我第一次直接加载索引视图时调试应用程序时,jQuery 函数被调用并正确调用控制器操作。http://localhost:51012/UserApplication/Index
但是当我再次加载视图时,jQuery 函数不会被调用。
控制器代码,
public JsonResult GetValidUserName(string userId)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string UserID = "";
objLMT.UserList = objLMTDAL.GetAll_User("", 0, "6");
var AllUsersInDatabase = from p in objLMT.UserList
where p.UserId == userId
select new
{
Name = p.UserName,
Id = p.UserId,
};
foreach (var user in AllUsersInDatabase)
{
if (user.Name != null)
{
UserID = user.Id;
}
}
return Json(UserID, JsonRequestBehavior.AllowGet);
}
【问题讨论】:
-
type: 'POST'=> 你确定控制器有[HttpPost]属性吗?也不必在contentType中添加JSON.stringify,只需使用data: { UserId: UserId }。检查您是否也遇到任何控制台错误。 -
你在哪里调用更改事件?作为普通脚本还是在 document.ready 方法中?
-
@TetsuyaYamamoto。是的,我已经进行了必要的更改,但仍然是同样的问题。
-
@mahlatse 在 document.ready 方法中。
-
可能您的参数名称不匹配:
data: { userId: UserId }。还要使用type: GET,因为您想通过 URL 查询字符串而不是FormData传递用户 ID。
标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-3