Catching a textbox value which is stored in a variable

时间:2015-06-26 09:58:28

标签: javascript asp.net-mvc-4

This is my controller.

 public class HomeController : Controller
  {
    public static string commString = "";

    public HomeController()
    {
      FWUtility.connString = "data source=.;initial catalog=northwind;uid=sa;password=123";
    }

    public ActionResult Index()
    {
      return View();
    }

    public static DataTable GetData(string customerID)
    {
      string strFilter = "'" + customerID + "%'";
      commString = "select * from customers where CustomerID like " + strFilter;
      return FWUtility.GetDataTable(commString);
    }

This is the view.

 <script type="text/javascript">
        function buttonClick() {
            var value = $('#text1').val();
            alert('@HomeController.GetData("D").Rows.Count.ToString()');
        }
    </script>
    <input type="text" id="text1" value="A" />
    <input type="text" id="text2" />
    <input type="button" value="Show" id="button1" onclick="buttonClick()" />

I want to catch the value which is stored in the textbox and display it in the alert box, where I have mentioned "D". In my controller I have a sql query assigned.And here I am calling the controller. My out put will be suppose I put "A" inside the text box and click the button, i will get the count of all the names starting with letter "A". Like this

2 个答案:

答案 0 :(得分:0)

It's not clear from the question, but assuming you want more than a simple alert(value), then:

I suggest that you add an additional action to go with the GetData function to return row count directly:

public ActionResult GetDataRowCount(string id)
{
    var count = GetData(id).Rows.Count;
    return new JsonResult
               {
                   Data = new { count },
                   JsonRequestBehavior = JsonRequestBehavior.AllowGet
               };

}

then you can use jquery ajax to get this value from the controller:

<script type="text/javascript">
    function buttonClick() {
        var value = $('#text1').val();

        $.get({
            url: '@Url.Action("GetDataRowCount", "Home")',
            data: { id = value }, 
            success: function(result) {
                alert(result.count);
            }
        });
    }
</script>
<input type="text" id="text1" value="A" />
<input type="button" value="Show" id="button1" onclick="buttonClick()" />     

答案 1 :(得分:0)

嗯,最后完成了。这是解决方案。

<script src="~/Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
    function buttonClick() {
        var value = $('#text1').val();
        $.ajax({
            url: '../Home/GetData',
            method: 'POST',
            data: { customerID: value },
            success: function (data) {
                result = data;
                alert(result);
            },
        });
    }
</script>
<input type="text" id="text1" value="A" />
<input type="button" value="Show" id="button1" onclick="buttonClick()" />