i cant populate select in jquery,my code is in razor c#, i try this - ajax

the content of the table is this
enter image description here
#section scripts{
<script>
function adddata() {
$.ajax({
type: "POST",
url: '?handler=GetItems',
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
data: { Id: $("#IdSelectIdPuesto").val() },
success: function (data) {
for (var i = 0; i < data.length; i++) {
$("#IdSelectlocalidad").append("<option value='" + data[i].value +
"' selected>" + data[i].text + "</option>");
}
},
error: function (result) {
alert("fail");
}
})
}
</script>
}
public JsonResult OnPostGetItems(int Id)
{
//displaydata1 = rTDBContext.Turnos.ToList();
var displayda = (from c in displaydata1
select c.LocNombre).Distinct().ToList();
return new JsonResult(new List<SelectListItem> = { new SelectListItem { Value = "1", Text = "LOcalidad" + 1 }, new SelectListItem { Value = "2", Text = "LOcalidad" + 2 } });
}
i'm trying a select distinct and add to the specified select the id and the locNombre to the text

If you want to change the options of $("#IdSelectlocalidad") with the id passed from ajax,here is a demo:
public JsonResult OnPostGetItems(int Id)
{
//displaydata1 = rTDBContext.Turnos.ToList();
var displayda = (from c in l
where c.Id==Id select new SelectListItem { Text=c.LocNombre, Value=c.Id+""}).Distinct().ToList();
return new JsonResult(displayda);
}
js(remove selected in the option,with the code it will select the first option by default):
#section scripts{
<script>
function adddata() {
$.ajax({
type: "POST",
url: '?handler=GetItems',
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
data: { Id: $("#IdSelectIdPuesto").val() },
success: function (data) {
for (var i = 0; i < data.length; i++) {
$("#IdSelectlocalidad").append("<option value='" + data[i].value +
"' >" + data[i].text + "</option>");
}
},
error: function (result) {
alert("fail");
}
})
}
</script>
}

[thanks Yiyi You, ifound the correct answer i doit this way]
[enter image description here][1]
[1]: https://i.stack.imgur.com/KWsIi.png do as folow
displaydata1 = rTDBContext.Turnos.ToList();
var display = displaydata1.DistinctBy(x => x.LocNombre ).ToList();
var displayda = (from c in display
select new SelectListItem { Text = c.LocNombre, Value = c.IdLocalidad + "" }).Distinct().ToList();
now is working as desired.

Related

Formdata empty on Controller even after calling append

On browse button click I have appended file(images) in FormData
and on Add Product button click I have to post Formdata via ajax to controller
but I am getting FromData as null on controller as well as on console.log.
Please let me know where I am going wrong.
Browse Button Click Event
$(document).ready(function () {
var _formData = new FormData();
$('.Btn_Browse').on('click', function () {
let input = document.createElement('input');
input.setAttribute('id', 'input_image')
input.setAttribute('multiple', 'multiple');
input.type = 'file';
input.onchange = _ => {
let files = Array.from(input.files);
if (files.length > 1) {
for (var i = 0; i < files.length; i++) {
_formData.append(files[i].name, files[i]);
}
};
input.click();
});
});
Add Product Button Click Event
$('#id_AddProduct').click(function (e) {
for (var key of _formData.entries()) {
console.log(key[0] + ', ' + key[1]);
}
$.ajax({
type: "POST",
url: "AddProduct",
contentType: false,
processData: false,
cache: false,
data: _formData,
success: function (response) {
},
failure: function (response) {
confirm("Your process is failed..");
},
error: function (response) {
confirm("Error occur during the process..");
}
});
});
Controller
public ActionResult AddProduct()
{
byte[] imagebyte = null;
int count = Request.Files.Count;
HttpFileCollectionBase Files = Request.Files;
for (int i = 0; i < Files.Count; i++)
{
HttpPostedFileBase httpPostedFileBase = Files[i];
if (httpPostedFileBase != null)
{
List<DALImage> imageList = new List<DALImage>();
if (Request.Files.Count > 0)
{
using (var br = new BinaryReader(httpPostedFileBase.InputStream))
{
var imgdata = br.ReadBytes(httpPostedFileBase.ContentLength);
DALImage objImg = new DALImage();
objImg.ImageName = httpPostedFileBase.FileName;
objImg.ImageTye = httpPostedFileBase.ContentType;
objImg.ImageData = Convert.ToBase64String(imgdata);
imageList.Add(objImg);
}
}
}
//string message = DAL.AddProduct(imageList, objProductDetails);
}
return Json(imagebyte, JsonRequestBehavior.AllowGet);
}

Populate One Dropdown on selection of other -MVC

I am trying to populate one dropdown list based on the selection of other dropdown list. This is what I have till now.
My Controller:
[HttpPost]
public JsonResult LoadReasonsByCategory(string resId)
{
var queryy = from item in db.T_SD_CD_GROUP
where resId.Contains(item.SCG_CD_TYPE)
select new
{
item.SCG_CD_TYPE,
item.SCG_CD_DESC
};
var ObjList = new List<SelectListItem>();
foreach (var item in queryy)
{
ObjList.Add(new SelectListItem() { Text = item.SCG_CD_DESC.ToString(), Value = (item.SCG_CD_TYPE) });
}
return Json(ObjList, JsonRequestBehavior.AllowGet);
}
JS
$("#ddlReasonCategory").on('change', function () {
var item = $(this).find("option:selected");
var value = $("#ddlReasonCategory").val(); //get the selected option value
//var text = item.html(); //get the selected option text
//alert(item.val());
$.ajax({
url: '/CRActual/LoadReasonsByCategory',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ resId: value}),
success: function (data) {
alert("sUccess");
$("#ddlReasonType").html("");
ddlReasonType.append($('<option></option>').val("").html("Please select a City"));
for (var i = 0; i < data.length; i++) {
ddlReasonType.append($('<option></option>').val(data[i].Text).html(data[i].Text));
}
},
error: function () {
alert("Fail")
},
});
View:
#Html.DropDownList("ddlReasonCategory", (IEnumerable<SelectListItem>)ViewBag.ddlReasonCategory, new { #class = "chosen-select col-md-3", #data_placeholder = "Please select" })
#Html.DropDownList("ddlReasonType", new SelectList(string.Empty, "Value", "Text"), "Please select a Reason", new { #class = "chosen-select col-md-3", #data_placeholder = "Please select" })
The codes runs absolutely without any errors, but the second drop down binding fails. Where am I going Wrong?
If your LoadReasonsByCategory method returns data correctly then write the success function code in the Ajax as follows:
success: function (data) {
var ddlResonTypeSelector = $("#ddlReasonType");
ddlResonTypeSelector.empty();
if (data.length > 0) {
ddlResonTypeSelector.append($("<option>").val("").text("Please select a Reason Type"));
$(data).each(function(index, item) {
ddlResonTypeSelector.append($("<option>").val(item.value).text(item.text));
});
} else {
ddlResonTypeSelector.append($("<option>").val("").text("Reason Type List is empty!"));
}
},

json response in ajax undefined

so here is my problem, I am returning a list of my model List from a controller through ajax. In response I am getting List but when i try to fill my datatable with this response it shows undefined everywhere
My View:
function GetData() {
pid = $(this).data('id');
var singleValues = $("#network").val();
var id = $(this).find(":selected").val();
var network = { "network": id };
$.ajax({
type: 'POST',
url: '/Home/GetData',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(network),
success: function (response) {
// console.log(response);
alert(response);
for (var i = 0; i < response.d.length; i++) {
$("#example").append("<tr><td>" + response.d[i].ACCOUNT_TYPE_ID + "</td><td>" + response.d[i].ACCOUNT_ISO_CODE + "</td><td>" + response.d[i].ACCOUNT_DESC + "</td></tr>");
debugger;
}
}
});
MY Controller:
[HttpPost]
public DbDataModel[] GetData(string network)
{
List<DbDataModel> l = new List<DbDataModel>();
DataTable db = GetDataSource(network);
foreach (DataRow row in db.Rows)
{
DbDataModel model = new DbDataModel();
model.Account_type_id = row["ACCOUNT_TYPE_ID"].ToString();
model.Account_iso_code = row["ACCOUNT_ISO_CODE"].ToString();
model.Account_desc = row["ACCOUNT_DESC"].ToString();
l.Add(model);
}
return l.ToArray();
}
My Model:
public class DbDataModel
{
public string Account_type_id { get; set; }
public string Account_iso_code { get; set; }
public string Account_desc { get; set; }
}
Change your method to return JSON
[HttpGet]
public JsonResult GetData(string network)
{
List<DbDataModel> l = new List<DbDataModel>();
.....
return Json(l, JsonRequestBehavior.AllowGet);
}
and in the script
...
$.ajax({
type: 'GET',
...
This is how i got it right.
function GetData() {
pid = $(this).data('id');
var singleValues = $("#network").val();
var id = $(this).find(":selected").val();
var network = { "network": id };
$.ajax({
type: 'POST',
url: '/Home/GetData',
dataType:"json",
traditional: true,
data: jQuery.param( network ),
success: function (response) {
debugger;
var oTable = $('#example').dataTable();//get the DataTable
oTable.fnClearTable();//clear the DataTable
for (var i = 0; i < response.length; i++) {
// $("#example").append("<tr><td>" + response[i].Account_type_id + "</td><td>" + response[i].Account_iso_code + "</td><td>" + response[i].Account_desc + "</td></tr>");
oTable.fnAddData([
response[i].Account_type_id,
response[i].Account_iso_code,
response[i].Account_desc
]);
}
}
});
};
[HttpPost]
public ActionResult GetData(string network)
{
List<DbDataModel> l = new List<DbDataModel>();
DataTable db = GetDataSource(network);
foreach (DataRow row in db.Rows)
{
DbDataModel model = new DbDataModel();
model.Account_type_id = row["ACCOUNT_TYPE_ID"].ToString();
model.Account_iso_code = row["ACCOUNT_ISO_CODE"].ToString();
model.Account_desc = row["ACCOUNT_DESC"].ToString();
l.Add(model);
}
return Json(l.ToArray(), JsonRequestBehavior.AllowGet);
}
Doing exactly what I wanted.

how to use cascading dropdownlist in mvc

am using asp.net mvc3, i have 2 tables in that i want to get data from dropdown based on this another dropdown has to perform.for example if i select country it has to show states belonging to that country,am using the following code in the controller.
ViewBag.country= new SelectList(db.country, "ID", "Name", "--Select--");
ViewBag.state= new SelectList("", "stateID", "Name");
#Html.DropDownListFor(model => model.Country, (IEnumerable<SelectListItem>)ViewBag.country, "-Select-")
#Html.DropDownListFor(model => model.state, (IEnumerable<SelectListItem>)ViewBag.state, "-Select-")
but by using this am able to get only the countries.
There is a good jQuery plugin that can help with this...
You don't want to refresh the whole page everytime someone changes the country drop down - an ajax call to simply update the state drop down is far more user-friendly.
Jquery Ajax is the best Option for these kind of questions.
Script Code Is Given below
<script type="text/javascript">
$(function() {
$("##Html.FieldIdFor(model => model.Country)").change(function() {
var selectedItem = $(this).val();
var ddlStates = $("##Html.FieldIdFor(model => model.state)");
$.ajax({
cache:false,
type: "GET",
url: "#(Url.Action("GetStatesByCountryId", "Country"))",
data: "countryId=" ,
success: function (data) {
ddlStates.html('');
$.each(data, function(id, option) {
ddlStates.append($('<option></option>').val(option.id).html(option.name));//Append all states to state dropdown through returned result
});
statesProgress.hide();
},
error:function (xhr, ajaxOptions, thrownError){
alert('Failed to retrieve states.');
statesProgress.hide();
}
});
});
});
</script>
Controller:
public ActionResult GetStatesByCountryId(string countryId)
{
// This action method gets called via an ajax request
if (String.IsNullOrEmpty(countryId))
throw new ArgumentNullException("countryId");
var country = GetCountryById(Convert.ToInt32(countryId));
var states = country != null ? GetStatesByConutryId(country.Id).ToList() : new List<StateProvince>();//Get all states by countryid
var result = (from s in states
select new { id = s.Id, name = s.Name }).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
Try this,
<script type="text/javascript">
$(document).ready(function () {
$("#Country").change(function () {
var Id = $("#Country").val();
$.ajax({
url: '#Url.Action("GetCustomerNameWithId", "Test")',
type: "Post",
data: { Country: Id },
success: function (listItems) {
var STSelectBox = jQuery('#state');
STSelectBox.empty();
if (listItems.length > 0) {
for (var i = 0; i < listItems.length; i++) {
if (i == 0) {
STSelectBox.append('<option value="' + i + '">--Select--</option>');
}
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
else {
for (var i = 0; i < listItems.length; i++) {
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
}
});
});
});
</script>
View
#Html.DropDownList("Country", (SelectList)ViewBag.country, "--Select--")
#Html.DropDownList("state", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "-- Select --")
Controller
public JsonResult GetCustomerNameWithId(string Country)
{
int _Country = 0;
int.TryParse(Country, out _Country);
var listItems = GetCustomerNameId(_Country).Select(s => new SelectListItem { Value = s.CountryID.ToString(), Text = s.CountryName }).ToList<SelectListItem>();
return Json(listItems, JsonRequestBehavior.AllowGet);
}

MVC3 and Twitter Bootstrap TypeAhead without plugin

I have gotten TypeAhead to work properly with static data and am able to call my controller function properly and get data but it is either A: Not parsing the data properly or B: The TypeAhead is not set up correctly.
JavaScript :
<input type="text" id="itemSearch" data-provide="typeahead" value="#ViewBag.Item" name="itemSearch"/>
$('#itemSearch').typeahead({
source: function (query, process) {
parts = [];
map = {};
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data, function (i, part) {
map[part.description] = part;
parts.push(part.description);
});
typeahead.process(parts);
}
});
},
updater: function (item) {
selectedPart = map[item].itemNumber;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp('(' + this.query + ')', 'gi');
return item.replace(regex, "<strong>$1</strong>");
}
});
Controller :
public ActionResult MakePartsArray(string query)
{
var possibleItem = query.ToLower();
var allItems = Db.PartInventorys.Where(l => l.ItemNumber.Contains(possibleItem)).Select(x => new { itemNumber = x.ItemNumber, description = x.Description });
return new JsonResult
{
ContentType = "text/plain",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems, },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
In my controller I see the data being retrieved correctly and it appears to parse properly but nothing is showing up for my TypeAhead.
Any idea on how to verify exactly where the breakdown is occurring or does anyone see direct fault in my code?
Problem was in the ajax call-
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data.matches, function (i, part) {
var composedInfo = part.description + ' (' + part.itemNumber + ')';
map[composedInfo] = part;
parts.push(composedInfo);
});
process(parts);
}
});
and in the controller on the return type
return new JsonResult
{
ContentType = "application/json",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

Resources