控制器代码:
public string ValidateCarID(string carid)//这里接收ajax传递过来的值
{
string result;
Car car = db.Car.Find(carid);//查找到传递过来的carid的实体对象
if(car==null)//如果没有找到该实体对象,返回false
{
result = "false"; //没有找到
}
else
{
result = "true";
}
return result;
}
ajax部分:
<script type="text/javascript">
$(document).ready(function () {
$("#carID").change(function () {//carID输入框改变事件
var caridNode = $("#carID").val();//获取CarID的值
$.ajax({
type: "post",
url: "../../Cars/ValidateCarID?carid=" + caridNode,//将CarID传到控制器,在控制器进行查询
dataType:"text",
success: function (result) {
if (result == "true") {
$.ligerDialog.error("该车辆已注册");
}
}
});
});
});
</script>
视图控件部分:
<tr>
<td>
@Html.LabelFor(model => model.CarID, htmlAttributes: new { @class = "control-label col-md-2" })
</td>
<td>
@Html.EditorFor(model => model.CarID, new { htmlAttributes = new { @class = "form-control",id="carID"} })//这个是需要判断的控件
@Html.ValidationMessageFor(model => model.CarID, "", new { @class = "text-danger" })
</td>
</tr>