DropDownList with java script - javascript

I hope developers can support me, I have minimal experience in the use of java script.
After investigating and several attempts, I was able to load a dropdownlist with data from a LINQ query and pass as a parameter the value of a textbox.
What I could not do is from the query Linq get two fields (Id and value) send them to the dropdownlist and show the value but after being able to use the Id of that field to be able to use it in a create, currently I can only show the value but I need the Id too.
View
#Html.TextBox("CP", "", new { #id = "txtCP", #onchange = "FillOption();", #placeholder = "Codigo Postal" })
#Html.DropDownList("Asentamientos", ViewBag.Drop as List<SelectListItem>)
Script
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.length; i++) {
$('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
}
}
});
}
</script>
Controllers
public ActionResult Index()
{
List<SelectListItem> drop = new List<SelectListItem>
{
};
ViewBag.Drop = drop;
return View();
}
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select p.Asentamiento).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
I think of something like
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
but I do not know how the id and the value would be handled
Thanks

If I understand your question correctly, I think you need to name the fields of the object you are creating with the Linq expression, so that it would look something like this:
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { id = p.IdCodigoPostal, value = p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
Here are a few examples: https://code.msdn.microsoft.com/LINQ-to-DataSets-09787825#SelectAnonymousTypes1
Then you could access those fields from you javascript with data[i].id and data[i].value.
I hope this helps.

I suspect your issue is around pulling the data from the API result. You're setting the a new property in the ViewBag, then returning the ViewBag property. This really shouldn't be required, and you should instead just return your list, list so (Note: and SelectItemList has a property called "Items" which contains all items you've added):
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
return Json(lista.Items);
}
This should return just a nice list of ListItems. You could also just change your jQuery to loop through the items property, like so:
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.Items.length; i++) {
$('#Asentamientos').append('<option value=' + data.Items[i].Value + '>' + data.Items[i].Text + '</option > ');
}
}
});
}
</script>

Thanks to all, the code works as follows
Controller
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { Value = p.IdCodigoPostal, Text= p.Asentamiento }).ToList();
SelectList lista = new SelectList(drop2);
return Json(lista.Items);
}
Script
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.length; i++) {
$('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
}
}
});
}

Related

Asp.net mvc dropdownlist cascading error Cannot set property 'value' of null

Hy.
I want to make dropdownlist cascadin. select dropdownlist and send editorfor.but
Cannot set property 'value' of null error .
I would like to send a value to editorfor a value of dropdownlist.
Can you help me?
public JsonResult GetPrice(string log)
{
int id = 1;
HomeController.sqlconnection con = new HomeController.sqlconnection();
string FIRMA = "select t.FIRMA,t.donem FROM dbo.TBLFRM as t where t.ID=" + id + "";
SqlCommand cmd = new SqlCommand(FIRMA, con.connect());
SqlDataReader rdrr = cmd.ExecuteReader();
rdrr.Read();
string firma = rdrr["FIRMA"].ToString();
string donem = rdrr["DONEM"].ToString();
ExtreModel item = new ExtreModel();
item.ItemList = new List<ExtreModel>();
string urun = "select P.PRICE from DBO.LG_" + firma + "_PRCLIST as p,DBO.LG_" + firma + "_ITEMS as I WHERE P.CARDREF=I.LOGICALREF AND P.CARDREF=" + log + "";
SqlCommand cmdd = new SqlCommand(urun, con.connect());
SqlDataReader rdr = cmdd.ExecuteReader();
rdr.Read();
string PRICE = rdr[0].ToString();
con.connect().Close();
return Json(PRICE, JsonRequestBehavior.AllowGet);
}
<script>
$("#LOGI").change(function () {
var select = $(this);
var cityname = select.val();
if (cityname != "") {
$.ajax({
method: "GET",
url: '/Mobil/GetPrice' + '?log=' + cityname,
beforeSend: function () {
}
}).done(function (result) {
document.getElementById("fyt").value = result.PRICE;
});
} else {
}
});
</script>
The problem seems coming from this return statement:
return Json(PRICE, JsonRequestBehavior.AllowGet);
This statement returns plain string value which doesn't contain PRICE property, so result.PRICE contains null value and causing null property assignment error message. If you want to return the price value, simply use this inside done function:
document.getElementById("fyt").value = result;
or in jQuery version:
$('#fyt').val(result);
But if you still want to return PRICE property, specify it inside JSON data:
return Json(new { PRICE = PRICE }, JsonRequestBehavior.AllowGet);
And the AJAX callback should be look like this:
$("#LOGI").change(function () {
var cityname = $(this).val();
if (cityname != "") {
$.ajax({
type: "GET",
url: '/Mobil/GetPrice',
data: { log: cityname }
}).done(function (result) {
$("#fyt").val(result.PRICE); // now the price property should exist
});
} else {
// do something else
}
});

mvc Ajax How to upate serialized model with formCollection

I have a page, which will send back the serialzed Model to the controller. In this case I'm using ajax.
In the View I have the following code:
#Html.Hidden("processViewModel", new Microsoft.Web.Mvc.MvcSerializer().Serialize(Model, SerializationMode.Signed))
And the controller looks like this:
[HttpPost]
public ActionResult PreviewSample([Deserialize]ProcessViewModel processViewModel /*FormCollection form*/)
and here is my ajax code:
function GetPreview() {
var json = $('form').serializeObject();
complete = false;
json['ProcessDTO.FileUploadDTO.TempUploadFileDTO.FileInformation.HasHeader'] = false; // $('input[name="ProcessDTO.FileUploadDTO.TempUploadFileDTO.FileInformation.HasHeader"]').is(':checked');
alert($('input[name="ProcessDTO.FileUploadDTO.TempUploadFileDTO.FileInformation.HasHeader"]').is(':checked'));
var jsonData = JSON.stringify(json);
var url = ROOT + '/request/previewsample/';
if (lastPreviewCall != undefined) {
if (lastPreviewCall.status != 200) {
lastPreviewCall.abort();
}
}
lastPreviewCall = $.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
// dataType: 'json',
data: jsonData,
otherParam: true,
async: true,
success: function (res) {
$('#preview').find('tbody').find('tr').remove();
var selected = $('.addressType:checked').attr('data-hideClass');
for (var i = 0; i < res.PreviewData.length; i++) {
var entry = '<tr>';
var row = res.PreviewData[i];
for (var u = 0; u < row.length; u++) {
if (u == 0 && selected == 'consumer') {
entry += '<td></td>';
}
else {
entry += '<td><span>' + row[u] + '</span></td>';
}
}
entry += '</tr>';
$('#preview').find('tbody').append(entry)
}
}
});
}
So now I have a checkbox, which is default true in this model and when I uncheck it, the ajax will send the serialized model back to the controller, but the checkbox has always the value true.
how can i update the model?
Thanks for any help.
The solution is to add
TryUpdateModel(processViewModel);
in the controller, and then is everything fine...

Refresh model after post-request in ASP.MVC

I'm developping a webApp with MVC.
I have a view with cirkles displaying a value and a slider,
when you slide the cirkles need to display the new value.
I send the new value with a POST from my AJAX call to the controller,
which does a minor calculation with the value and give it back to the view
so the cirkles can display the updated value.
However my view still keeps using the startvalue.
#model UGT.UI.Web.MVC.Models.BelastingViewModel
<script language="JavaScript">
var config1 = liquidFillGaugeDefaultSettings();
#{
teller = 1;
string naam_var = null;
foreach (KeyValuePair<UGT.BL.Domain.BegrotingPackage.Categorie, double> cat in Model.Belasting)
{
naam = "fillgauge" + teller;
naam_var = "gauge" + teller;
#: var #naam_var = loadLiquidFillGauge("#naam", "#Html.DisplayFor(modelItem => cat.Value)", config1);
teller++;
}
}
function toonCirkels() {
#{
teller = 1;
naam = "fillgauge" + teller;
string naam_var2 = null;
foreach (KeyValuePair<UGT.BL.Domain.BegrotingPackage.Categorie, double> cat in Model.Belasting)
{
naam_var2 = "gauge" + teller;
// #: gauge1.update("#Html.DisplayFor(modelItem => cat.Value)");
// #: var #naam_var = loadLiquidFillGauge("#naam", "#Html.DisplayFor(modelItem => cat.Value)", config1);
// #: #naam_var2.update("#Html.DisplayFor(modelItem => cat.Value)");
teller++;
}
//#:gauge1.update("500");
}
}
public class BelastingsController : Controller
{
private BegrotingsManager begrotingsManager = new BegrotingsManager();
private int gemeenteId = 54;
private double loon = 200;
private BelastingViewModel belastingen = new BelastingViewModel();
// GET: Belastings
public ActionResult Index()
{
var belasting = begrotingsManager.GetBelastingGebruiker(this.loon, gemeenteId);
belastingen.Belasting = belasting;
UpdateModel(belastingen);
return View(belastingen);
}
[HttpPost]
public ActionResult Index(String loon)
{
this.loon = Double.Parse(loon);
var belasting = begrotingsManager.GetBelastingGebruiker(this.loon, gemeenteId);
belastingen.Belasting = belasting;
UpdateModel(belastingen);
return new HttpStatusCodeResult(HttpStatusCode.OK);
// return RedirectToAction("Index");
}
namespace UGT.UI.Web.MVC.Models
{
public class BelastingViewModel
{
public IDictionary<Categorie, double> Belasting { get; set; }
}
}
d3.selectAll('.range').on('change', function () {
this.value = parseInt(this.value);
if (this.value < 0) this.value = 0;
else if (this.value > 5000) this.value = 5000;
var loon = this.value;
var loonString = "€" + loon;
d3.select('.range_value').html(loonString);
sendLoon(loon, loonString);
});
}
function sendLoon(loon, loonString) {
$.ajax({
contentType: "application/json; charset=utf-8",
url: "/Belastings",
type: "POST",
data: JSON.stringify({ "loon": loon }),
success: function () {
// window.location.reload();
toonCirkels();
},
error: function () { }
});
}
The success of your Ajax call calls 'toonCirkels' which only contains razor generated code which is filled on page load. The content of this method never changes as it contains ONLY razor generated code and thus will always have the same logic with the same values.

Binding Kendo Data Source with Async $.ajax calling from C# MVC Controller Action

This is my action in controller. Which return a List> converting into DataSourceResult.and also Serializing into Json.
[HttpPost]
public ActionResult GetMissingShiftData([DataSourceRequest]DataSourceRequest request)
{
DataTable dtResponse = new DataTable();
var dynamicList = new List<dynamic>();
var myMainList = new List<List<dynamic>>();
List<DataSourceResult> viewResultList = new List<DataSourceResult>();
string RigNumber = string.IsNullOrWhiteSpace( resultData.Filter.SelectedRig.RigNumber) || resultData.Filter.SelectedRig.RigNumber == "ALL" ? "" : resultData.Filter.SelectedRig.RigNumber;
DataSet response = MissingShiftsReportData.GetData(Convert.ToDateTime(resultData.Filter.DateStart), Convert.ToDateTime(resultData.Filter.DateEnd), ConnString, RigNumber);
foreach (DataTable dt in response.Tables)
{
dtResponse = dt;
string[] columnNames = dtResponse.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
foreach (DataRow dr in dtResponse.Rows)
{
dynamic myObj = new ExpandoObject();
var p = myObj as IDictionary<string, object>;
Regex rgx = new Regex("[^a-zA-Z0-9]");
for (int i = 0; i < columnNames.Length; i++)
{
string name = dr.Table.Columns[i].ColumnName.Replace(" ", String.Empty);
name = name.Replace(".", String.Empty);
name = name.Replace("(", String.Empty);
name = name.Replace(")", String.Empty);
name = rgx.Replace(name, "");
p[name] = dr[i];
}
dynamicList.Add(p);
}
myMainList.Add(dynamicList);
}
DataSourceResult viewResult = myMainList.ToDataSourceResult(request);
string JsonViewData = JsonConvert.SerializeObject(viewResult.Data);
return new ContentResult { Content = JsonViewData, ContentType = "application/json", ContentEncoding = Encoding.UTF8 };
}
And this is the async call I am doing with Jqery.while I am trying to bind a data source it shows "data[0].Data" is "undefined". How can I make use of 'data'.
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var list = data[0].Data;
var dataSource = new kendo.data.DataSource({
data: data[0].Data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});
You are serializing an array (the Data property) and don't need to use the Data field at the client-side:
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var dataSource = new kendo.data.DataSource({
data: data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});

Jqgrid ui autocompletion : Disable Case sensitivity

In my JQgrid i have a ui atocomplete column which are Case sensitive.
For example i have 2 Items in my grid: Ivan and ivan, if i type "i" autocomplete will return only ivan.
I have tryed to make a function inside of source: but i failed since my ajax call always return object Object instead of an item. Any ideas?
Code for autocomplete:
$(elem).autocomplete({
delay: 0,
minLength: 0,
source: function (req, response) {
alert(req);
$.ajax({
mtype: "post",
url: '#Url.Action("GetBrands")',
dataType: "json",
async: false,
cache: false,
data: { term: req },
success: function (data) {
alert(data);
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
response($.grep(data, function (item) { return matcher.test(item.value); }));
}
});
},
Controller side code:
public virtual JsonResult GetBrands(string term)
{
if (term == null) term = string.Empty;
var vendorId = _service.GetVendorIdByUsername(GetUserName());
var brands = _service.GetBrandsByVendor(vendorId);
var brand = new BrandsViewModel();
brand.BrandName = "Opret ny Brand...";
brands.Add(brand);
foreach (var brandsViewModel in brands)
{
if (brandsViewModel.BrandName == "Intet")
{
brandsViewModel.BrandName = "";
}
}
return Json((from item in brands
where item.BrandName.Contains(term)
select new
{
value = item.BrandName
//votes = item.Votes,
}).ToArray(),
JsonRequestBehavior.AllowGet);
}
convert it all to one case when compering:
public virtual JsonResult GetBrands(string term)
{
if (term == null) term = string.Empty;
term = term.ToLower();
var vendorId = _service.GetVendorIdByUsername(GetUserName());
var brands = _service.GetBrandsByVendor(vendorId);
var brand = new BrandsViewModel();
brand.BrandName = "Opret ny Brand...";
brands.Add(brand);
foreach (var brandsViewModel in brands)
{
if (brandsViewModel.BrandName == "Intet")
{
brandsViewModel.BrandName = "";
}
}
return Json((from item in brands
where item.BrandName.ToLower().Contains(term)
select new
{
value = item.BrandName
//votes = item.Votes,
}).ToArray(),
JsonRequestBehavior.AllowGet);
}

Categories