michal demjančuk michal demjančuk - 2 months ago 17
ASP.NET (C#) Question

How to make event on textbox.text_changed (ASP.NET)

Hi i have no idea with creating event textchanged or somethink as this for textBox.
It will be doing some form of find when text changed.

Image with code



@{
ViewBag.Title = "Index";
<br />
using (Html.BeginForm())
{
<p>
<p>
@Html.TextBox("searchString")
<input type="submit" value="Find" />
</p>
</p>
}
}

<h2>Index</h2>





I want it call this (This is written right):

public ActionResult Index(string searchString)
{
if (String.IsNullOrWhiteSpace(searchString))
{
return View(db.Regions.ToList());
}
else
{
List<Regions> collectionOfRegions = db.Regions.ToList();
return View(collectionOfRegions.Where(x => x.MatchBetweenAllFields(searchString)));
}
}

Answer

Replace TextBox

@Html.TextBox("YourTextBox", new { onchange="yourForm.submit();"})

And add JavaScript

<script type="text/javascript">
        $(function () {
            $('#YourTextBox').change(function () {
              //Content to send 
              var yourText = $(this).val();

              //Post the content of your Textbox to your "YourAction" action in "YourController"
              $.post('@Url.Action("YourAction","YourController")', { "YourText" : yourText }, function(data){
                  //Do something with the results here
                  alert(data);
              });
            });
        });
</script>

Also edit controller

[HttpPost]
public void YourAction(string yourText)
{
      if (String.IsNullOrWhiteSpace(yourText))
    {
        return View(db.Regions.ToList());
    }
    else
    {
        List<Regions> collectionOfRegions = db.Regions.ToList();
        return View(collectionOfRegions.Where(x => x.MatchBetweenAllFields(yourText)));
    }
}