我的Ajax代码是
function UserCheck() {
var q = document.getElementById("username").value;
$.ajax({
url: '@Url.Action("Checks","Ajaxx")',
data: {
'userdata': q
},
type: "POST",
dataType: "html",
success: function (data) {
//------------
alert("insuccess");
document.getElementById("username").innerHTML = data.toString();
}
});
}
Am使用此Ajax代码检查输入的用户名是否存在 我的控制器名称是Ajaxx,方法是checks
方法是
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CinemaApplication.Models;
namespace CinemaApplication.Controllers
{
public class AjaxxController : Controller
{
//
// GET: /Ajaxx/
[HttpPost]
public string Checks(string userdata)
{
string tmp = "success";
using (OurDbContext db = new OurDbContext())
{
var SeachData = db.Logins.Where(x => x.username == userdata).FirstOrDefault();
if (SeachData != null)
{
tmp = "Fail";
}
}
return tmp;
}
}
}
这是我控制器的全部代码。它专用于此ajax。 用户名字段的值已正确到达q,但我不知道controller(Ajaaxx)中的方法(检查)是否有效
答案 0 :(得分:1)
尝试在jquery调用中使用以下属性:
dataType: 'json',
contentType: "application/json; charset=utf-8"
答案 1 :(得分:0)
Ajax代码
function Checks()
{
var unm = document.getElementById("username").value;
$.ajax({
type: "POST",
url: "/Ajaxx/Checks",
data: '{user:"' + unm + '"}',
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(result)
{
var mess = $("#Status");
if (result)
{
mess.html('Username available');
mess.css("color", "green");
}
else{
mess.html('Username not available');
mess.css("color", "red");
}
}
});
}
</script>
var mess持有范围的ID 控制器
[HttpPost]
public JsonResult Checks(string user)
{
bool tmp = true;
using (OurDbContext db = new OurDbContext())
{
var SeachData = db.Logins.Where(x => x.username == user).FirstOrDefault();
if (SeachData != null)
{
tmp = false;
}
}
return Json(tmp);
}