0

如何添加 MVC3 自动完成文本框更改事件?下面是我的代码。

我的查看代码

<div style="float: left">

States Filter :

</div>

<div style="float: left; padding-left: 10px">
   @Html.TextBox("Statestxt")
</div>

<div style="padding-left: 10px; float: left">
   <input type="image" value="submit" src="../../Images/FilterBrowse.gif" 
          alt="submit Button" />    
</div>

我的控制器:

public ActionResult AutocompleteAsync(string term)
{  
    var suggestions = from s in Adm.states
    select s.state_name;
    var namelist = suggestions.Where(n => n.ToLower().StartsWith(term.ToLower()));

    return Json(namelist, JsonRequestBehavior.AllowGet);
}


[AcceptVerbs(HttpVerbs.Post)]   
public ActionResult States(state stateModel, string _stateName, 
    FormCollection formvalues)
{  
   AdmDataContext Adm  = new AdmDataContext;

   if (Request.Form["Statestxt"] == null)
   {
      ViewBag.Error = "Enter State Name.";   
      ViewData["name"] = false;

      return View();
    }
    else
    {
        _stateName = Request.Form["Statestxt"].ToString();
        var record = (from state in Adm.states
                      where state.state_name == _stateName
                      select state).Count();

        if (record == 0)
        {
           ViewBag.Error = "Enter Valid State Name.";

           return View();

        }

        var _Stateid = from state in Adm.states
                       where state.state_name == _stateName
                       select state;

        int StateId = (int)_Stateid.First().state_id;
        var state1 = am.FindUpcomingStates2(StateId).ToList();

        if (state1 != null)
        {
            ViewData["name"] = true;
            return View("States", state1);
        }

     }
}

我想在输入Statestext后更改数据。我在哪里可以编写文本框更改事件的代码?

谢谢。

4

1 回答 1

0

我认为您想在用户更改文本时调用 Javascript 函数。Html.TextBox 帮助器有一个重载,您可以使用它:

@Html.TextBox("Statestxt", "", new { onkeyup = "fnAjaxAutocomplete(this)" })

然后您的处理程序 Javascript 方法将如下所示:

function fnAjaxAutocomplete(element)
{
    var ajaxUrl = '@Url.Action("AutocompleteAsync")' + '?text=' + element.value;
    $.get(ajaxUrl(function(suggestionsJson) {
        // handle JSON result here
    });
}
于 2012-04-12T05:16:38.310 回答