Hi all I have to implement one Dropdownlist which contains the image with country code and one textbox associated with that i am sharing you all the below screenshot which i
As far as I see, dropdown
and textbox
are different and are aligned next to each other. Depending on dropdown
item selection textbox
value is changed.
For having image for dropdown check following link
http://fairwaytech.com/2012/08/adding-images-select-lists-mvc3/
This looks like a textbox with auto complete feature enabled on that. You can use any autocomplete plugin like jQuery UI library autocomplete to achieve this.jQuery ui allows you to customize the autocomplete option item's HTML markup to include the image.
The first step is to load the jQuery, jQuery UI libraries to your page.
Next, In our view, we need a textbox where we need this feature.
<input id="countrySearch" value="" />
Next step is to write an action method in your controller which returns the data you want in JSON format.
public ActionResult Countries(string term)
{
var list=new List<CountryVM>();
// Hardcoding 2 items for demo.
//to do : read data from your db and build the list.
list.Add(new CountryVM { ID=1,Name="US",FlagImg="http://yoursite/usa.jpg"});
list.Add(new CountryVM { ID=2,Name="IN",FlagImg="http://yoursite/in.jpg"});
return Json(list, JsonRequestBehavior.AllowGet);
}
Assuming you have a viewmodel called CountryVM
like
public class CountryVM
{
public int ID { set;get;}
public string Name { set;get;}
public string FlagImg { set;get;}
}
So this action method will return JSON data like this.
[
{
"ID": "1",
"Name": "US",
"FlagImg": "http://yoursite/usa.jpg"
},
{
"ID": "1",
"Name": "US",
"FlagImg": "http://yoursite/in.jpg"
}
]
Let's go back to client side, In out view we have our textbox, now we need to enable autocomplete plugin on that textbox. By default, the plugin will render a listitem(<li>
) in the auto suggest dropdown. We need to tell the plugin to build our customized markup (Which includes the flag image) instead. We can use the create
method to do the customization we want. So have this javascript code to do that.
<script type="text/javascript">
$(function(){
$("#countrySearch").autocomplete({
source: function (request, response) {
$.ajax({
url: "@Url.Action("Countries","Home")",
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.ID,
image: item.FlagImg };
}))
}
})
},
create: function () {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
return $('<li>')
.append("<a><div><img src='" +item.image+ "' />"
+item.label+"</div></a>")
.appendTo(ul);
};
},
select: function (event, ui) {
//you can access ui.item to get the selected item object.
console.log("Selected item id : " + ui.item.value);
return false;
}
});
});
</script>
That's it. This should give you the autocomplete feature with images inside that.