Pass kendo grid model in Ajax call - c#

I need to pass kendo grid model (on save event) to the server side in an ajax call. How can i do that? Tried the following
function onSave(e) {
var keys = Object.keys(e.values);
var colName = keys[0];
var alignment;
var mapHeaderId = $('#ddlMaps').val();
var yearId = $('#ddlYear').val();
$.get("#Url.Action("CalculateFormattingForResult", "Maps")", { studentId: e.model.studentid, colId: colName, value: e.values[colName], mapHeaderId: mapHeaderId, yearId: yearId,
model: JSON.stringify(e.model)
}, function (data) {}
}
My C# code is
public string CalculateFormattingForResult(int studentId, string colId, string value, int mapHeaderId, int yearId, string model) {
}
If someone is interested into why i am doing that..is because i need to get the latest edited values in the grid based on which i have to calculate/update other values in the grid.
UPDATE
I tried it with $.post and it worked but with post the problem is that probably i can only submit the form once however, i am only doing data validation on edit event of each cell...so i need to do it again and again. so my question is still there... how do i pass json string which is [kendo dataItem (row)] in ajax??

The problem was i had to put a $.post instead of $.get..found answer here:passing json in ajax
Also, as I mentioned in update, second time kendo grid model changes like this
originaljson + edited values as json
for example: firstname:"samra", surname:"abc" becomes firstname:"samra", surname:"abc" , firstname:"sarah", surname:"xyz"
In my case the newer values contained html divs (to format cells), so it was not getting posted!.

Related

Subtracting 2 Dates from Database

I have 2 Dates which I pull out from a database. One being a Start Time and One being an End Time. I am wanting to find the difference between the 2 dates and then display the time taken between the 2 on the same page.
I have seen this code on other answers but I am new to this so not sure where to place it and then display it on a page.
var ExecutionSeconds = execution.End.Subtract(execution.Start).TotalSeconds;
Any help would be greatly appreciated.
Thanks
The first Thing is that you Need a DbContext in your conroller to get execution from you database. Then you can execute your code line to determine the time span in seconds.
The second part is to give this value to your view. For example by passing it to the View-method as the model:
//fetch your data and calculate ExecutionSeconds...
return View(ExecutionSeconds);
}
Inside the View you can access your model by declaring the #model element and accessing the Model property:
#model Int32
#* other HTML code you need *#
<span>The timespan is #Model seconds long</span>
One way is to have read only property on the model
public int ExecutionDiff{
get{
return this.End.Subtract(this.execution.Start).TotalSeconds;
}
}
Or put calculated value to the ViewData or ViewBag and take value from there
one way to have the below function which gives you the difference in days.If you want to check difference in js change the function appropiately.
public int DayDiffrenceInt(DateTime date1, DateTime date2)
{
var a = (date2.Date - date1.Date).Days;
return a;
}
If your query contains StartDate and EndDate, Then you can subtract each row this way:
var dateQuery = dateTimeQuery.Select(p => p.StartDateTime - p.EndDateTime).ToList();
Then you can assign that query in a ViewBag:
ViewBag.DateTimes = dateQuery;
So inside your view you can easily show it:
foreach (var dateTime in ViewBag.DateTimes)
{
<li>#dateTime.TotalSeconds</li>
}
I managed to solve this using ViewBag.
Controller
ViewBag.ExecutionSeconds = (execution.End - execution.Start).TotalSeconds;
View
#ViewBag.ExecutionSeconds

Kendo UI: Get MultiSelect selected values as a comma separated string

I'd appreciate if someone could help with my issue.
I have an entity with field PAYMENT_CURRENCIES of string type, that should store comma separated values, i.e. "USD,EUR,AED" (or any other separation char).
In my View:
#Html.Kendo().MultiSelectFor(model => model.Contract.PAYMENT_CURRENCIES).BindTo(context.Currencies).DataTextField("CODE").DataValueField("CODE").Placeholder("Add currency...")
The problem is when I submit the form i receive only first selected value in the Controller.
I would not like to change the datatype of the field for IEnumerable.
Is there a way to receive all selected values as a string with some separator?
Thanks a lot
I don't think that you can automatically convert your multi select input value(s) to a single string.
So what you can do is:
Use a viewModel (ContractViewModel) which contains a List
Or use javascript to "convert" your input value(s) to a single string separated with any separator you want
Add an array-property to your model:
public string[] PAYMENT_CURRENCIES_LIST
{
get
{
return PAYMENT_CURRENCIES?.Split(',');
}
set
{
PAYMENT_CURRENCIES = string.Join(",", value);
}
}
Then use this property in your view:
#Html.Kendo().MultiSelectFor(model => model.Contract.PAYMENT_CURRENCIES)...
So the array-property maps to the Kendo-Multiselect and translates the values to/from the original field.
I had the same requirement as yours, & couldn't find a decent solution, That's how I solved it:
Create a new Property in your ViewModel public List<string> SelectedCurrencies { get; set; }
Configure your MultiSelect Kendo helper to bind to the newly created property #Html.Kendo().MultiSelectFor(model => model.SelectedCurrencies)
.BindTo(context.Currencies)
.DataTextField("CODE")
.DataValueField("CODE")
.Placeholder("Add currency...")
To Save: Now when you hit your action method, just set your comma separated field PAYMENT_CURRENCIES = string.Join(",", viewModel.SelectedCurrrencies);
To Read: SelectedCurrencies = PAYMENT_CURRENCIES.Split(',').ToList();

Getting an ID of a value from dropdown list

Hey,
I Have three IQueryable lists which i concat together into one list to be displayed in the dropdown box. But now I want to get the id of what the user selected since there are 3 lists to choose from. Thanks
Example:
IQueryable<Store> stores= _storeRepository.FindAll().OrderBy(c => c.Description);
var storeList = stores.ToSelectList("StoreId", "Description", viewModel.StoreId.ToString());
IQueryable<Product> products = _productRepository.FindAll().OrderBy(j => j.Name);
var productList = products.ToSelectList("ProductId", "Name", viewModel.ProductId.ToString());
var viewList = storeList.Concat(productList).ToList();
viewModel.Lookups = viewList; //display in dropdown
if you question was i have 3 lists and the user choose one how can i know which one he chosen
Answer :
you give all three the same name and the value will change depend on which one the user have chosen
if your question was i want to send the id value with the selected list
Answer :
the server doesn't have any info about your html attributes
just the name attribute which maps to the action method parameter name and the value which maps to the parameter value , you can't know the id value and other attributes in the server
Example :
<input type="text" name="Title" id="SomeValue"/>
Will Map To :
public ActionResult Index(string Title)
the server will not recive id="SomeValue"
Solution :
What you can do is place a hidden field under every item with the value you want
instead of this way, after concatenating do this
viewdata["viewList"] = storeList.Concat(productList).ToList();
and view display items in dropdown like this
<%= Html.DropDownList("viewlist_id", (List<SelectListItem>)ViewData["viewlist"])%>
now use a submit button (if want to post the data to same action else use actionlink with routvalues if redirecting to different action,I am using here submit button)
<input type="submit" name="submit" value="submit" />
and in your action you can retrieve the posted data
var dropdown_id = Request.Form["viewlist_id"];
this way you will get the id of selected drop down. thanks
So i figured out how to have the values of different lists combined into one dropdown list will still being able to access its actual value or ID without concat or union- the code is a lot if anyone is interested i will go ahead and take the time to properly post it. Other than that, thank you everyone for offer your advise and help. Thanks
So this is how i went about my problem. In my Controller File - in my Get method after the button click this is what i did:
resultSummaryViewModel.Value = value;
resultSummaryViewModel.ReportFrame = new FramedViewModel();
if(value !="")
{
string viewValue = value.Substring(0, value.IndexOf("|"));
string viewType = value.Substring(value.IndexOf("|") + 1);
resultSummaryViewModel.ReportFrame.SourceURL =
WebPathHelper.MapUrlFromRoot(
string.Format(
"Reporting/ResultSummary.aspx?beginDate={0}&endDate={1}&Id={2}&viewType={3}",
resultSummaryViewModel.BeginDate, resultSummaryViewModel.EndDate, viewValue,
viewType));
}
var viewData = new Dictionary<string, string>();
viewData.Add("Schools", "|allschools");
viewData.Add("Classes", "|allclasses");
This is also connected to my display page aspx.cs which contains the actual lists i use to populate.

Retrieving selected item text within a JsonResult function

I am creating an MVC project with a table using the JQGrid plugin. I would like to use a DropDownList to allow the user to specify a value, that will be used in an SQL query to retrieve specific data from the table. I.e. user can select a country from the list, and the table will display items only from that country.
My problem is, that I cannot figure out how to retrieve the selected item from the DropDownList, within my data bind function for my table, within my controller class.
DropDownList in the View
<%= Html.DropDownList("Countries")%>
Setting up the DropdownList in my controller
//dt is a DataTable which holds the values for my list
List<SelectListItem> countries = new List<SelectListItem>();
for (int i = 0; i < dt.Rows.Count; i++)
countries.Add(new SelectListItem { Text = dt.Rows[i][0].ToString(), Value = "" + i });
JsonResult DataBind() method where I would like to access the selected value
public JsonResult Charges_DataRequested()
{
string country = "Dropdownbox Selected Text";
}
The problem seems to be that within a JsonResult function I don't have access to the ViewData or my ViewModel, which always seem to be null when I try and access them. I am very new to MVC and web development, any advice would be very welcome.
Thanks for the answer, it put me on the right track. I realized that the grid also has a postdata parameter. I was able to create a javascript postback function for my dropdownlist, and call the jqGrid 'setGridParam' function to add my dropdownlist text to the grid postdata. I could also trigger a grid reload, and grab the string in my controller Jsonresult function.
The Javascript
$('#Countries').change(function() {
var value = $("#Countries option:selected").text();
$("#ChargesGrid").setGridParam ({
postData:{
selectedCountry:$("#Countries option:selected").text()}
});
$("#ChargesGrid").trigger("reloadGrid");
alert(value);
});
The controller
public JsonResult Charges_DataRequested(string selectedCountry)
{
string country = selectedCountry;
}
jqGrid has got a userdata property where you could store this data so it would be available on post. It may mean you'd have to update this dropdown changes.
jQuery("#GridId").getGridParam('userData').SelectedText
I've only used this the other to set data on loading but think it could work the other way around for you. I would have set the SelectedText above in a controller action when creating the grid json as
userdata = new { SelectedText = "SomeValue" }
The only trouble would be if it were a private set equivalent within the jqGrid code.

Retrieve DataItem from RepeaterItem after databinding (during an event handler)

I'm trying to find a way to to do something that I think must be possible but I'm just missing the point on - so hopefully someone can give me a bit of a nudge :)
I'm utilising databinding in ASP.NET (viewstate turned off - so using controlstate for a few things here and there) to render a repeater (repeaterPriceClasses) that has a repeater within each itemtemplate (repeaterPriceBands). Basically this renders a table out of some text and a dropdownlist in each cell.
I'm trying to find a way to enumerate the repeaterOuter inside the event handler of a button to give me a list of all of the originally bound elements that have now got a dropdownlist with a value of >0, along with what that value is.
public Dictionary<Price, int> SelectedPrices
{
get
{
var sel = new Dictionary<Price, int>();
foreach(RepeaterItem itemClass in repeaterPriceClasses.Items)
{
var repeaterPriceBands = itemClass.FindControl("repeaterPriceBands") as Repeater;
foreach(RepeaterItem itemBand in repeaterPriceBands.Items)
{
var context = (Price)itemBand.DataItem;
var listQty = itemBand.FindControl("listQty") as DropDownList;
if(listQty.SelectedValue.ToInt32() > 0)
{
sel.Add(context, listQty.SelectedValue.ToInt32());
}
}
}
return sel;
}
}
Now this fails because the itemBand.DataItem is always null after databinding has finished.
What technique should I use to get around this?
Hidden field with primary keys in it
(not ideal as can be abused and adds
weight to the page)
Lookup from
original cached data based on indexes
(just seems wrong)
or something
else/better...?
EDIT: Is there any more information that I could provide to help this get answered?
You can try adding extra attributes to your HTML elements in the ItemDataBound event when DataItem is available.
ddlSomething.Attributes["Attribute1"] = dataItemObject.PropertyName;
[Edit]
Apart from using attributes, you can render some array containing JSON objects like this, for each row.
var repeaterItemAttributes = [ { Prop1: val1, Prop2: val2, ... }, { ... }, ... ]
So, by using this, you won't have to render the attributes, and your code will be XHTML compliant too (tho its not required). You can then loop through the object array and read any property you like. You can also apply the light encryption you were talking about to the property values.
[/Edit]

Categories

Resources