Display incremented count from database table ID using Ajax - c#

I want to get the last ID from a database table and increment by 1, to be displayed in an Input or Label parameter of HTML.
Most tutorials display it in tables. Here is my code:
index.cshtml
<td>Trans Id</td>
<td><input id="tbTransID" type="text" /></td>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/CashAdvance/GetTransID",
data: "{}",
success: function (data) {
var s = data.TransID;
}$("#tbTransId").html(s);
}
});
});
</script>
CashAdvanceController
public ActionResult GetTransID()
{
AcctgContext db = new AcctgContext();
return Json(db.CATransactions.Select(x => new
{
TransID= x.TransID + 1
}).ToList(), JsonRequestBehavior.AllowGet);
}

You need to change your linq query in the controller as below:
public ActionResult GetTransID()
{
AcctgContext db = new AcctgContext();
return Json(db.CATransactions.OrderByDescending(i => i.TransID).Select(i=>new
{
TransID= x.TransID + 1
}).FirstOrDefault(), JsonRequestBehavior.AllowGet);
}
In your query, you are selecting list of values whereas you need only the max id to increment it.

Related

Ajax call is passing controller name and method name instead of data

I am running into some trouble with my ajax call. Here is the controller code:
[Route("RatingInfo/HandleRequest")]
[HttpPost]
public ActionResult HandleRequest(Dictionary<string, string> textBoxValues)
{
var result = CreateJson(textBoxValues); // This is a simplified example
return Json(result);
}
And here is my Jquery/ajax (Razor syntax):
function PassData () {
var data = {};
$('.divCell input').each(function (index, item) {
var id = $(item).attr('id');
var value = item.value;
data['dictionary[' + index + '].Key'] = id;
data['dictionary[' + index + '].Value'] = value;
});
$.ajax({
url: '#Url.Action("HandleRequest")',
type: 'POST',
dataType: 'JSON',
traditional: true,
data: data,
sucesss: function (result) {
alert('Success');
}
})
}
The idea here is to get the data from each textbox and pass it back to the server as a Dictionary with the id as the key and value as, well, the value.
Stepping through the Chrome debugger, the JS data object is built successfully.
From the debugger:
Local
data: Object
dictionary[0].Key: "Address"
dictionary[0].Value: "123 Main St"
dictionary[1].Key: "ZipCode"
dictionary[1].Value: "99999"
dictionary[2].Key: "Phone1"
dictionary[2].Value: "(555) 555-5555"
...
__proto__: Object
However, when the data is passed back to the controller, the values inside textBoxValues does not contain the passed data. Rather, it contains two key/value pairs with keys controller and action and values the names of the controller and action.
From the Visual Studio debugger:
textBoxValues = Count = 2
[0] = {[controller, RatingInfo]}
[1] = {[action, HandleRequest]}
How can I get Jquery to pass the data rather than the controller/action names? I am confused as to how this can even happen in the first place. Any help would be appreciated.
UPDATE
Sorry, I had put wrong code in.
The reason why this was not working is because the name of the parameter was incorrect, giving you a mismatch.
The below will work for you. Notice the name of dictionary is changed to your parameter textBoxValues:
function PassData() {
var data = {};
$('.divCell input').each(function (index, item) {
var id = $(item).attr('id');
var value = item.value;
data['textBoxValues[' + index + '].Key'] = id;
data['textBoxValues[' + index + '].Value'] = value;
});
$.ajax({
url: '#Url.Action("HandleRequest")',
type: 'POST',
traditional: true,
data: data,
sucesss: function (result) {
alert('Success');
}
})
}

How to format a date/time being returned from database to only show the time segment

I have a cascading dropdownlist that is populated using a jQuery script. Each Item in the list I want to display a code and a start time. Something like:
C123 (7:30 am)
D345 (9:00 am)
I am having trouble working out how to format the date/time to show only the time in the list.
<script type="text/javascript">
$(document).ready(function () {
$("#Shift").prop("disabled", true);
//Dropdownlist Selectedchange event
$("#StationList").change(function () {
$("#Shift").empty();
if ($("#StationList").val() != "Select a Station") {
$.ajax({
type: 'POST',
url: '#Url.Action("GetShiftsByStation")', // we are calling json method
dataType: 'json',
data: { selectedValue: $("#StationList").val() },
// here we are get value of selected Station and passing same value as input to json method GetShifts.
success: function (shiftList) {
// states contains the JSON formatted list
// of shifts passed from the controller
$("#Shift").append('<option value="' + null + '">' + "Please select a shift" + '</option>');
$.each(shiftList, function (i, shift) {
$("#Shift").append('<option value="' + shift.Value + '">' + shift.Text + '</option>');
// here we are adding option for shifts
$("#Shift").prop("disabled", false);
});
},
error: function (ex) {
alert('Failed to retrieve shifts.' + ex);
}
});
return false;
}
else {
$("#Shift").empty();
$("#Shift").prop("disabled", true);
}
})
});
</script>
The JQuery calls GetShiftsByStation in the controller
public JsonResult GetShiftsByStation(string selectedValue)
{
//Created object of service class which holds the method that queries database.
DataAccess DataAccessService = new DataAccess();
//Created a list of string to hold shifts from Database.
List<SelectListItem> shiftList = new List<SelectListItem>();
//Populating the list by calling GetShiftsByStationId method of service class.
shiftList = DataAccessService.GetShiftsByStationId(Convert.ToInt32(selectedValue));
//Returning the list using jSon.
return Json(new SelectList(shiftList, "Value", "Text"));
}
which calls GetShiftsByStationId(int stationId) to query the database and return a list of shifts for each location.
Method
//Gets the shift list based on StationId which is foreign key in Shifts table.
public List<SelectListItem> GetShiftsByStationId(int stationId)
{
//Created DataContext to query DB.
using (DataManager db = new DataManager())
{
//returns all the records from table based on StationId in list format.
return db.Shifts.Where(query => query.StationId == stationId).Select(s => new SelectListItem { Value = s.ShiftId.ToString(), Text = s.Code + " (" + s.Start + ")" }).ToList();
}
}
So where and how am I best to format the date/time that is returned from the database?
I tried to use s.Start.ToString("t") but that didn't work because of course .ToString("t") is not supported in the LINQ query.
use this instead of s.Start
DbFunctions.CreateTime(s.Start.Hour, s.Start.Minute, s.Start.Second)
If you are not using EF6 use EntityFunctions instead of DbFunctions

Why my drop down list items are invisible?

I am trying to make 2 cascading drop down lists.
First one works fine, you pick an item but when you go to the second drop down list, you can actually see correct number of spaces generating according to the items in the database but not the items themselves!
Its like they are invisible!
Can you please advise?
My View :
#using (Html.BeginForm("Browse", "Bookings", new { id = "TypeItemFormID", data_itemsListAction = #Url.Action("ItemsList") }))
{
<fieldset>
<legend> Type/Item</legend>
#Html.DropDownList("department", ViewBag.ItemTypesList as SelectList, "Select a Type", new {id="ItemTypeID"})
<div id="ItemsDivId">
<label for="Items">Items </label>
<select id="ItemsID" name="Items"></select>
</div>
<p>
<input type ="submit" value="Submit" id="SubmitID" />
</p>
</fieldset>
}
<script type="text/javascript">
$('#ItemTypeID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function (results) {
var options = $('#ItemsID');
options.empty();
options.append($('<option />').val(null).text("- Select an Item -"));
$.each(results, function () {
options.append($('<option />').val(this.ItemsID).text(this.Value));
});
}
});
});
</script>
My Controller :
[HttpPost]
public JsonResult GetItemTypeForm(string itemTypeId)
{
//pseudo code
var data = from s in db.Items
where s.ItemType.ItemTypeName == itemTypeId
select s.ItemName;
return Json(data);
}
You have the initial problem I mentioned in my comment, but it appears from your comments that your member names probably do not match either.
This may not be exact, as we do not know all your data/member names, but you may want something like this (using an anonymous type to return the shape of data you expect):
[HttpPost]
public JsonResult GetItemTypeForm(string itemTypeId)
{
//pseudo code
var data = from s in db.Items
where s.ItemType.ItemTypeName == itemTypeId
select new { Value = s.ItemName, ItemsID = s.ItemId };
return Json(data);
}

How can I modify this Select2 javascript to enable paging?

I am not too familiar with javascript, so I need help here. I have this method which returns a list of Customers (2000+), so the Select2 dropdown hangs. I want to enable paging, but I am not sure what I need to change. Here is my javascript code:
var GetCutomerDDL = function(cient) {
var Json = {},
customers = [];
$ddlCustomers.select2('val', '');
Json.client = cient;
$.post(urlContent + 'Cutomer/GetCustomerDDL', Json, function(data) {
}, 'json').done(function(data) {
customers = data;
$ddlCustomers.select2({
placeholder: "Select Customer(s)",
allowClear: true,
multiple: true,
data: customers
});
});
};
GetCustomerDDL uses LINQ to just return all the customers, but I want to enable paging so don't load over 2000 records in a dropdown at once. What do I need to change in the javascript and the server side?
The Select2 control includes "infinite scrolling". That may be what you're looking for.
Scroll2's main page is found here: http://select2.github.io/
On the server-side, you'll want to use Skip() and Take() LINQ operators to skip forward in the data and to take only a certain number of items from your data. Select2 should pass which items to skip and take to your controller.
Edit:
Try changing this:
$.post(urlContent + 'Cutomer/GetCustomerDDL', Json, function(data) {
}, 'json').done(function(data) {
customers = data;
$ddlCustomers.select2({
placeholder: "Select Customer(s)",
allowClear: true,
multiple: true,
data: customers
});
});
to this:
$ddlCustomers.select2({
ajax: {
url: urlContent + 'Cutomer/GetCustomerDDL',
dataType: 'json',
data: function (term, page) {
return {
q: term, // search term
pageLimit: 10,
page: page, // page number
client: client
};
},
results: function (data, page) {
var more = (page * 10) < data.total; // whether or not there are more results available
return { results: data.customers, more: more };
}
},
});
On your controller, you'll want to return your sub-list of customers in a "customers" property, and the total customers in a "total" property.
return Json(new { customers = customers.Skip(...).Take(...),
total = customers.Count() }, JsonRequestBehavior.AllowGet);
Sample json result:
{ customers: [...], total: 2000 }

ASP.NET / Ajax - How do you pass a parameter in your call?

I am trying to filter down my results and can't figure out how to set up the ajax query to work properly with the select2 drop down. From what I can tell you are supposed to use data, but that is not passing just the value in and filtering down my call.
Here is my ajax:
$('#e1').select2({
placeholder: "Select an ingredient...",
minimumInputLength: 2,
ajax: {
url: "../api/IngredientChoices",
data: 'mi',
dataType: "json",
quietMillis: 500,
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page
};
},
results: function (data, page) {
var more = (page * 10) < data.length;
console.log(more);
console.log(data);
return { results: data, more: more };
},
formatResult: function (post) {
markup = '<strong>' + post.text + '</strong>';
}
}
});
Here is my controller:
public List<Models.IngredientChoices> Get(string param)
{
var choices = (from i in _context.IngredientItems_View(param)
select new Models.IngredientChoices
{
id = i.ItemID,
text = i.ConcatName,
});
return choices.ToList();
}
The ajax call returns all values currently.
you have a duplicate member data: on your ajax - you should only have one.
EDIT: just a SWAG but perhaps you need a class:
class myparam {
string q ;
int page_limit;
int page;
}
//decorate for JSON
public List<Models.IngredientChoices> Get(myparm param)
{
var choices = (from i in _context.IngredientItems_View(param.q)
The answer, as #jmordyk said was that my q: term did not match my parameter in c#. I changed this line:
public List<Models.IngredientChoices> Get(string param)
to be:
public List<Models.IngredientChoices> Get(string q)

Categories