Link to home
Start Free TrialLog in
Avatar of ukerandi
ukerandiFlag for United Kingdom of Great Britain and Northern Ireland

asked on

C# MVC Auto completed issue

Hi Experts,

I have issue with my code. But when i'm debugging and i can see records are coming but it's not properly display in the web page


User generated imageSee debug results
User generated image
Jquery example from  : https://jqueryui.com/autocomplete/#default
@section Scripts {
    <script>
             $(function () {
            var availableTags = [
                "ActionScript",
                "AppleScript",
                "Asp",
                "BASIC",
                "C",
                "C++",
                "Clojure",
                "COBOL",
                "ColdFusion",
                "Erlang",
                "Fortran",
                "Groovy",
                "Haskell",
                "Java",
                "JavaScript",
                "Lisp",
                "Perl",
                "PHP",
                "Python",
                "Ruby",
                "Scala",
                "Scheme"
            ];
            $("#tags").autocomplete({
                source: 'api/JobSearch/search'
            }

            );
        });



    </script>

    @{await Html.RenderPartialAsync("_ValidationScriptsPartial"); }

Open in new window

but if I replace with this  Source :
 $("#tags").autocomplete({
                source:availableTags

Open in new window

it will work for availableTag Array. 
Html
  <div class="form-group">

        <div class="col-md-12">
            @Html.EditorFor(model => model.JobNumber, new { htmlAttributes = new { @class = "form-control" } })



        </div>
    </div>

Open in new window

APIcontroller
 [Route("api/[controller]")]
    [ApiController]
    public class JobSearchController : ControllerBase
    {
        
        public JobSearchController()
        {
                
        }
        [Produces("application/json")]
        [HttpGet("Search")]
        public async Task<IActionResult> Search()
        {

            try
            {

                string term = HttpContext.Request.Query["term"].ToString();
                SqlConnection con = new SqlConnection(connectionname);
                //select the Job number
                //===================================================================================================
                con.Open();

                SqlCommand jobSqlCommand = con.CreateCommand();
                jobSqlCommand.CommandText = "FindJobNumbersp";
                jobSqlCommand.CommandType = CommandType.StoredProcedure;
                jobSqlCommand.Parameters.Add("@Search", SqlDbType.NVarChar).Value = term;
                List<jobDetails> Joblist = new List<jobDetails>();
                SqlDataAdapter da = new SqlDataAdapter(jobSqlCommand);
                DataSet ds = new DataSet();
                da.Fill(ds);
                foreach (DataRow dr in ds.Tables[0].Rows)
                {

                    Joblist.Add(new jobDetails
                    {
                        JobNumber = dr["job"].ToString()

                    }
                    ); ;

                }
                jobSqlCommand.Dispose();
                con.Close();
                return Ok(Joblist);

            }
            catch (Exception)
            {

                return BadRequest();
            }


        }

Open in new window

_Layout.cshtml
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - TestJquery</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
    <link href="~/lib/jquery-ui-1.12.1.custom/jquery-ui.min.css" rel="stylesheet" />
    <link href="~/lib/datetimepicker-master/datetimepicker-master/build/jquery.datetimepicker.min.css" rel="stylesheet" />

    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">

</head>

Open in new window

_ValidationScriptsPartial.cshtml


<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>


Open in new window


if anyone can show why is data is not displaying ,i will really appreciated.


Avatar of Dorababu M
Dorababu M
Flag of India image

Can you show the logic of how you are attaching the result to drop down?
Avatar of ukerandi

ASKER

@Dorababu M  Thank you very much for reply
Html
  <div class="form-group">

        <div class="col-md-12">
            @Html.EditorFor(model => model.JobNumber, new { htmlAttributes = new { @class = "form-control" } })



        </div>
    </div>

Open in new window


JQUERY
@section Scripts {
    <script>
             $(function () {
         
            $("#JobNumber").autocomplete({
                source: 'api/JobSearch/search'
            }

            );
        });

Open in new window



also tried like this
Html  - Search area
<div class="col-md-12">
    Enter Job to search       <input asp-for="JobNumber" id="JobNumber" class="ui-autocomplete" />



        </div>

Open in new window


Jquery
@section Scripts {
    <script>
             $(function () {
          
            $("#JobNumber").autocomplete({
                source: 'api/JobSearch/search'
            }

            );
        });

      

    </script>

    @{await Html.RenderPartialAsync("_ValidationScriptsPartial"); }


}

Open in new window



Is there any controller you are calling after you enter a key in text box?
The Jquery example you have given will work this way if you have written any code on controller side and binding it
 $("#JobNumb").autocomplete({
  source: function (request, response) {
  $.ajax({
       url: '/api/JobSearch/search/',
       data: "{'prefix': '" + request.term + "'}",
       dataType: "json",
       type: "POST",
       contentType: "application/json; charset=utf-8",
       success: function (data) {
           response($.map(data, function (item) {
           return item;
       }))
     },
      error: function (response) {
        alert(response.responseText);
      },
      minLength: 1
  });

Open in new window

Code on mvc
[HttpPost]
    public JsonResult Search(string prefix)
    {
        var job = yourquery.ToLoist()
 
        return Json(job);
    }


Open in new window

@Dorababu M 

Is there any controller you are calling after you enter a key in text box?
Yes
See following control.This API Control
[Route("api/[controller]")]
    [ApiController]
    public class JobSearchController : ControllerBase
    {
                public JobSearchController()
        {
                        }
        [Produces("application/json")]
        [HttpGet("Search")]
        public async Task<IActionResult> Search()
        {

            try
            {

                string term = HttpContext.Request.Query["term"].ToString();
                SqlConnection con = new SqlConnection(connectionname);
                //select the Job number
                //===================================================================================================
                con.Open();

                SqlCommand jobSqlCommand = con.CreateCommand();
                jobSqlCommand.CommandText = "FindJobNumbersp";
                jobSqlCommand.CommandType = CommandType.StoredProcedure;
                jobSqlCommand.Parameters.Add("@Search", SqlDbType.NVarChar).Value = term;
                List<jobDetails> Joblist = new List<jobDetails>();
                SqlDataAdapter da = new SqlDataAdapter(jobSqlCommand);
                DataSet ds = new DataSet();
                da.Fill(ds);
                foreach (DataRow dr in ds.Tables[0].Rows)
                {

                    Joblist.Add(new jobDetails
                    {
                        JobNumber = dr["job"].ToString()

                    }
                    ); ;

                }
                jobSqlCommand.Dispose();
                con.Close();
                return Ok(Joblist);

            }
            catch (Exception)
            {

                return BadRequest();
            }


        }

Open in new window

But where is the logic to bind the results to control?

 <script>
             $(function () {
                      $("#JobNumber").autocomplete({
                source: 'api/JobSearch/search'
            }
// do you have any code here? after returning results from controller
            );
        });



Open in new window

Avatar of louisfr
louisfr

For autocomplete to display something, you must either return a list of strings, or a list of objects with a label and/or value property.
I tried using this,But not working
 $(document).ready(function () {
            $("#JobNumber").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: 'api/JobSearch/search',
                        type: 'POST',
                        dataType: 'json',
                        data: {Prefix:request.term},
                        success: function (data) {
                            response($.map(data, function (JobNumber) {
                                return {
                                    label: item.JobNumber,
                                    value: item.JobNumber
                                }
                            }))
                        }
                    });
                },
                minLength: 2
        });

Open in new window

also tried this code ,But the event also not working so i can't debug
I have use following Example : @louisfr  if you  check this example you can see there is no code after Source
https://jqueryui.com/autocomplete/#default

 $(document).ready(function () {
            $("#JobNumber").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/api/JobSearch/search/',
                        data: "{'prefix': '" + request.term + "'}",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data, function (item) {
                                return item;
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        minLength: 1
            });
        });

Open in new window

Is your JobNumber is defined as string? I tried the following code and it works
Here is my model
public class JobDetail
    {
        public int JobNumber { get; set; }
        public string JobName { get; set; }
    }

Open in new window

May be try your controller by changing it to JSON as follows
[HttpPost]
        public JsonResult AutoComplete(string prefix)
        {
            String[] jobName = { "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion","Erlang",
            "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" };
            List<JobDetail> jobDetails = new List<JobDetail>();
            for (int i = 0; i < 20; i++)
            {
                JobDetail j = new JobDetail();
                j.JobNumber = i;
                j.JobName = jobName[i];
                jobDetails.Add(j);
            }
            var jobDets = (from job in jobDetails
                           where job.JobName.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)
                           select new
                           {
                               label = job.JobName,
                               val = job.JobNumber
                           }).ToList();
            return Json(jobDets);
        }

Open in new window

Finally in Jquery
<script type="text/javascript">
    $(function () {
        $("#JobName").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '/Home/AutoComplete/',
                    data: "{'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data, function (item) {
                            return item;
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            minLength: 1
        });
    });
</script>

Open in new window


Output is as follows
User generated image
Check your browser console if it is showing any errors?
Dorababu M Yes.Thank you very much for reply
That's way working for me also. But when i'm trying to get data from Database it's not working.

This way working - without connect to database

var result1 = new[] { @"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",
    "Clojure", "COBOL", "ColdFusion", "Erlang","Fortran", "Groovy","Haskell",
    "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python","Ruby", "Scala", "Scheme" };


                return Ok(result1.Where(x =>
       x.StartsWith(term, StringComparison.CurrentCultureIgnoreCase)).ToArray());


Open in new window


But when I have add to the database , not working

 [Produces("application/json")]
        [HttpGet("Search")]
        public async Task<IActionResult> Search()
        {

            try
            {

                string term = HttpContext.Request.Query["term"].ToString();
                SqlConnection con = new SqlConnection(connectionname);
                //select the Job number
                //===================================================================================================
                con.Open();
             
                SqlCommand jobSqlCommand = con.CreateCommand();
                jobSqlCommand.CommandText = "FindJobNumbersp";
                jobSqlCommand.CommandType = CommandType.StoredProcedure;
                jobSqlCommand.Parameters.Add("@Search", SqlDbType.NVarChar).Value = term;
                List<jobDetails> Joblist = new List<jobDetails>();
                SqlDataAdapter da = new SqlDataAdapter(jobSqlCommand);
                DataSet ds = new DataSet();
                da.Fill(ds);
                foreach (DataRow dr in ds.Tables[0].Rows)
                {

                    Joblist.Add(new jobDetails
                    {
                        JobNumber = dr["job"].ToString()
                         
                }
                    ); ;
                 //result = new[] { dr["job"].ToString() };
                }
                jobSqlCommand.Dispose();
                con.Close();
               
                return Ok(Joblist);


            }
            catch (Exception)
            {

                return BadRequest();
            }


        }

Open in new window

How is your Joblist  return Ok(Joblist);  looks like?
OK try this
return item.JobNumber;

Open in new window

Instead of
return item;

Open in new window

User generated image
You marked your method with
[HttpGet("Search")]

Open in new window

and your ajax call with
type: "POST"

Open in new window

Try changing one of them, HttpPost, or type "GET"
Thanks
I tried using like this :
HTML

<div class="ui-widget">
            <input asp-for="JobName" id="JobName" />
        </div>

  @section Scripts {
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

        <script type="text/javascript">
            $(function () {
                $("#JobName").autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            url: '/Home/AutoComplete/',
                            data: "{'prefix': '" + request.term + "'}",
                            dataType: "json",
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            success: function (data) {
                                response($.map(data, function (item) {
                                    return item;
                                }))
                            },
                            error: function (response) {
                                alert(response.responseText);
                            },
                            failure: function (response) {
                                alert(response.responseText);
                            }
                        });
                    },
                    minLength: 1
                });
            });
        </script>
}

Open in new window

Home Controller Code
   [HttpPost]
        public JsonResult AutoComplete(string prefix)
        {
            String[] jobName = { "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion","Erlang",
            "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" };
            List<jobDetails> jobDetails = new List<jobDetails>();
            for (int i = 0; i < 20; i++)
            {
                jobDetails j = new jobDetails();
                j.JobNumber1 = i;
                j.JobName = jobName[i];
                jobDetails.Add(j);
            }
            var jobDets = (from job in jobDetails
                           where job.JobName.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)
                           select new
                           {
                               label = job.JobName,
                               val = job.JobNumber1
                           }).ToList();
            return Json(jobDets);
        }

Open in new window



Problem is here is this
User generated image

and prefix value is NULL

After add the
prefix = HttpContext.Request.Query["term"].ToString();


it will get data from Array but when you are typing it's not filtering

Like this

[HttpPost]
        public JsonResult AutoComplete(string prefix)
        {
            prefix = HttpContext.Request.Query["term"].ToString();
            String[] jobName = { "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion","Erlang",
            "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" };
            List<jobDetails> jobDetails = new List<jobDetails>();
            for (int i = 0; i < 20; i++)
            {
                jobDetails j = new jobDetails();
                j.JobNumber1 = i;
                j.JobName = jobName[i];
                jobDetails.Add(j);
            }
            var jobDets = (from job in jobDetails
                           where job.JobName.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)
                           select new
                           {
                               label = job.JobName,
                               val = job.JobNumber1
                           }).ToList();
            return Json(jobDets);
        }


Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Dorababu M
Dorababu M
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Try removing the contenttype line and passing a json object instead of a string.
data: { prefix: request.term }