当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - how to pass id of selected record from autocompletion textbox to controller

问题描述:

 public class Product

{

public int Id { get; set; }

public string ProductName { get; set; }

public double Weight { get; set; }

public double PurchaseRate { get; set; }

public double SaleRate { get; set; }

public string Details { get; set; }

public int Vendor { get; set; }

public string VendorCode { get; set; }

public int VendorId { get; set; }

public string VendorName { get; set; }

public string ProductCode { get; set; }

}

above is my product class and in product controller i have a method vendorlist which returns json ,this methos is as below

public ActionResult vendorList(string term)

{

var results = new[]

{

new { id = "1", label = "Suraj Metels" },

new { id = "2", label = "A.B. Infra" },

new { id = "3", label = "Momin Brother" },

new { id = "4", label = "Fort"},

new { id = "5", label = "Malabar Hill" },

};

var result3 = results.Where(s => s.label.ToLower().Contains(term.ToLower())).Select(w => w).ToList();

return Json(result3, JsonRequestBehavior.AllowGet);

}

below is view code for create view

 <div class="span6" >

<div class="span4" >

<label >Vendor</label>

</div>

<div class="span6" >

@Html.TextBox("VendorName",null, new { id = "SearchBox", @class = "SearchBox" })

</div>

</div>

and jquery code is as below

 <script type="text/javascript">

$(function () {

$('.SearchBox').autocomplete({

source: '@Url.Action("vendorList")',

minLength: 1,

select: function (evt, ui) {

}

});

});

autocomplition functionality works here.but when i select a vendorname and when i pass this data to "create" controller, i want to send id of particular record.

for ex. if i select vendor name as "Suraj Metels" then i want to send id=1 to controller.

please help me

网友答案:

you can make ajax call in select function as below

$('.SearchBox').autocomplete({
        source: '@Url.Action("vendorList")',

        minLength: 1,

        select: function (evt, ui) { 
                $.ajax({
                    url: "MethodName",
                    dataType: "json",
                    data : ui.item.value,
                    success : function(response) {
});             
              });

        }
    });
网友答案:

Try this

var results = new[] 
         {
        new { id = "1", label = "Suraj Metels", yourUrl=Url.RouteUrl("RouteName",new {id="1"}) },
        new { id = "2", label = "A.B. Infra", yourUrl=Url.RouteUrl("RouteName",new {id="2"})},
        new { id = "3", label = "Momin Brother", yourUrl=Url.RouteUrl("RouteName",new {id="3"})},
        new { id = "4", label = "Fort",  yourUrl=Url.RouteUrl("RouteName",new {id="4"})},
        new { id = "5", label = "Malabar Hill", yourUrl=Url.RouteUrl("RouteName",new {id="5"})},

        };

In select

select: function( event, ui ) {

                            window.location=ui.item.yourUrl;
                            return false;
                        }
网友答案:

This should work:

select: function (event, ui) {
           var url = '@Url.Action("YourAction", "YourController", new { id = "__id__" })';
           window.location.href = url.replace('__id__', ui.item.id);
        }
网友答案:

below code is works for passing id of selected record from autocomplition textbox to controller. using this code you can select string value and you can pass id of that record to controller.

$('#ProductList').append("<div  class='span12' style='margin-left:0px' ><div class='span2'>" +
           // "<select class='clsProductId '  name='ProductId' id='ddProductList_" + IDD + "' style = 'font-size:12px;width:200px;margin-right:80px;margin-left:20px;' onchange='get(" + IDD + ")'/> </div>" +
         "<input type='text' class='ProductName span1 pull-left' id='ProductNameID_" + IDD + "' name='Productname' value='' style = 'font-size:12px;width:200px;margin-right:80px;margin-left:20px;' placeholder='start typing to load products' /> " +
           "<input type='hidden' class='ProductName1 ' id='Pid_" + IDD + "' name='ProductID' value=''  /> " + "<hr></div>");

this code is for dynamicaly create textbox for product name. and hidden textbox for id.

below code for autocomplete event

  $(".ProductName").on("focusin", function () {
            $(this).autocomplete({
                source: '@Url.Action("GetProductList","Product")',
                minLength: 1,                   
                select: function (evt, ui) {                     
                    newlabel = ui.item.label;
                    newlabelId = ui.item.id;

                    $('input.ProductName').attr('id');
                    var ProductName_id = $(this).prop('id');
                    var Product_Name_Index = parseInt(/ProductNameID_(\d+)/.exec(ProductName_id)[1], 10);

                    $('#Pid_' + Product_Name_Index).val(newlabelId);
                    getProductDetails(newlabelId, Product_Name_Index);                      
                }
            });
       });

and controller method is as below

public JsonResult GetProductList(string term)
    {          
        var product_list = GetProductList();

        var Final_Products= product_list.Where(s => s.ProductName.ToLower().StartsWith(term.ToLower())).Select(product => new { id= product.Id,label=product.ProductName }).ToList();

        return Json(Final_Products, JsonRequestBehavior.AllowGet);

    }

in above method "GetProductList()" is list of product.term is a letter from which we want to find name of product.

And when you want to pass id of selected recodto httppost method then use "string[] ProductID" . Here ProductID is vale of name attribute of id.

[HttpPost]

public ActionResult Create(string[] ProductId)

{ //your code

}

分享给朋友:
您可能感兴趣的文章:
随机阅读: