我正在尝试使用jquery执行类似asp.net textchanged事件的操作。当我使用自动完成更改一个tetbox值时,另一个文本框上会有更改。数据将来自我的数据库。假设我有两个文本框txtOne和TxtTwo。当我使用自动完成更改txtone时txtTwo值会将accorindg从数据库更改为txtOne。 这是我的代码。我究竟做错了什么?我怎样才能在mvc。
中的同一文本框中实现自动完成和文本切换事件 @Html.TextBoxFor(model => model.ITEMNM, htmlAttributes: new { @class = "form-control", id = "txtOne" })
@Html.TextBoxFor(model => model.ITEMNM, htmlAttributes: new { @class = "form-control", id = "txtTwo" })
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#txtOne').autocomplete(
{
source: '@Url.Action("TagSearch", "RMS_ITEM")'
});
});
$(function () {
$('#txtOne').change(function () {
var changedText = $("#txtOne").val();
$.post('@Url.Action("ItemNameChanged","RMS_ITEM")', { "ChangedText": changedText });
});
});
</script>
这是我的控制器代码
[HttpPost]
public ActionResult ItemNameChanged(string changedText)
{
var result = (from n in db.PosItemMstDbSet
where n.CATNM == changedText
select new
{
catid = n.CATID
}
);
foreach (var n in result)
{
ViewBag.itemId = n.catid;
}
//return changedText + " was submitted!";
return null;
}
public JsonResult TagSearch(string term)
{
var compid = Convert.ToInt16(System.Web.HttpContext.Current.Session["loggedCompID"].ToString());
var tags = from p in db.PosItemMstDbSet
where p.COMPID == compid
select p.CATNM;
return this.Json(tags.Where(t => t.StartsWith(term)),
JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:2)
这是我的脚本代码
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#txtItemNm').autocomplete(
{
source: '@Url.Action("TagSearch", "RMS_ITEM")',
change: txtOneChanged
});
});
function txtOneChanged()
{
var changedText = $("#txtItemNm").val();
var txtBox = document.getElementById('catid');
$.getJSON(
"/RMS_ITEM/ItemNameChanged", { "ChangedText": changedText },
function (myData) {
txtBox.value = myData;
});
}
</script>
这是我的控制器方法
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult ItemNameChanged(string changedText)
{
var compid = Convert.ToInt16(System.Web.HttpContext.Current.Session["loggedCompID"].ToString());
var itemId = "";
var rt = db.PosItemMstDbSet.Where(n => n.CATNM == changedText &&
n.COMPID == compid).Select(n => new
{
catid = n.CATID
});
foreach (var n in rt)
{
itemId = n.catid;
}
return Json(itemId, JsonRequestBehavior.AllowGet);
}
public JsonResult TagSearch(string term)
{
var compid = Convert.ToInt16(System.Web.HttpContext.Current.Session["loggedCompID"].ToString());
var tags = from p in db.PosItemMstDbSet
where p.COMPID == compid
select p.CATNM;
return this.Json(tags.Where(t => t.StartsWith(term)),
JsonRequestBehavior.AllowGet);
}
答案 1 :(得分:0)
您需要为自动填充调用定义change
选项:
$("#txtOne").autocomplete(
{
source: '@Url.Action("TagSearch", "RMS_ITEM")'
change: txtOneChanged
});
function txtOneChanged()
{
// your custom code
}
看看这个JSFiddle: