KendoUI : data-bind not fully working - asp.net

I created this sample locally
http://demos.telerik.com/kendo-ui/mvvm/remote-binding
In my 'update' transport, I did modify the 'ProductName' from my WebAPI
public IHttpActionResult Update(Product prod)
{
prod.Price = prod.UnitPrice * prod.Quantity;
prod.ProductName = prod.ProductName + DateTime.Now.ToString();
return Ok(prod);
}
It did update and reflect on my 'dropdownlist'.
The issue is the textbox id=products is not showing the latest productname. The textbox is binded using
data-bind="value: selectedProduct.ProductName"
How can I refresh this text box ?
Thank you.
All is same except this
update: {
url: "/Product/Update",
contentType: "application/json",
type: "POST"
},
and this.
parameterMap: function (data, type) {
return kendo.stringify(data);
}
If these changes are not made; my webapi will not receive any value.
I notice like the binding somehow got broken momentarily; is it because its indirectly reference using the var 'selectedProduct' ?

The reason, I believe, that your textbox is not updating is because of two reasons: 1) you're changing the data on the server instead of the client, and 2) the textbox is tied to the selectedProduct variable which is in no way tied to the data source.
In other words, when you submit the update, because your dropdown list is bound to the productSource data source, it's data gets updated automatically and the list is refreshed to show you the changes. This is expected. On the other hand, selectedProduct is not tied to the data source in any way, so, it still holds the old value before the update was called.
The solution is you have to manually update selectedProduct after the update request returns.

Related

Wijimo Autocomplete & AngularJS - setting initial value from loaded data

I am trying to set the initial value in a Wijimo Autocomplete control which has been loaded from an external data source. The scenario being a form is used to create some new data and then is saved. Subsequently the data needs to be edited so it is reloaded into the form.
I can successfully use the Autocomplete on the initial form - the source list is a JSON Array of objects which is loaded into the controller. The app is using UI Router so I resolve this first.
When I save the data I serialise the selected Object from the Autocomplete control and is then saved to a Mongo DB store. When loading this data back in it is converted back to an object.
This is what the control looks like:
<wj-auto-complete
selected-index="selectedIndexCombo"
selected-item="selectedAirline"
items-source="airlineCodes"
display-member-path="Title"
placeholder="Airline Code"
max-items="50"/>
An example of the source list looks like this:
{
"#href":"\/airline.nsf\/api\/data\/collections\/name\/(LUAirlines)\/unid\/8DCD734E7BCDA24D80257C99003770C4",
"#link":
{
"rel":"document",
"href":"\/airline.nsf\/api\/data\/documents\/unid\/8DCD734E7BCDA24D80257C99003770C4"
},
"#entryid":"98-8DCD734E7BCDA24D80257C99003770C4",
"#unid":"8DCD734E7BCDA24D80257C99003770C4",
"#noteid":"FB2",
"#position":"98",
"#siblings":100,
"#form":"Airline",
"AirlineCode":"WN",
"Airline":"Southwest Airlines",
"Title":"WN - Southwest Airlines"
}
So when the form is initially created the controller property selectedAirline is correctly set with the selected Object.
So this works fine in the save function:
$scope.formData.selectedAirline = JSON.stringify($scope.selectedAirline);
But when reloading in the data:
AirlineInfoFactory.loadAirlineInfo($scope.reference).then(function success(response) {
$scope.selectedAirline = eval('(' + response.data.selectedAirline + ')');
$scope.information = response.data.information;
$scope.dataLoaded = true;
console.log($scope.selectedAirline)
$scope.selectedIndexCombo=11;
})
The autocomplete control does not bind to the selectedAirline property.
I tried using the selected-index attribute on the directive so see if I could just change it to something when the data loads but it doesnt work either. I suspect its to do with the digest loop but I am not sure.
Any ideas?
Thanks
I tried to replicate the scenario by reloading the data and setting the selectedAirline property and it works well withe latest version 32. Here is the fiddle:
http://jsfiddle.net/n1kpkcud/2/
` $scope.countries = initialList;
$scope.selectedAirline = '';
$scope.setItem = function () {
$scope.countries = reloading;
$scope.selectedAirline = 'Yemen';
}`
I would suggest you to update this fiddle so that it replicates the issue and I can suggest you accordingly.

ASP.Net Drop Down List not passing a value when updated using ajax

I have some jQuery that I'm using to open a pop-up window where a new consignor can be added to the database. The original window has a dropdownlist of all of the current consignors. When you add the new consignor in the pop-up window, that window closes and the original window then reloads the dropdownlist's data and selects the one just created.
All of that works perfectly. My issue is that when you fill out the rest of the form and submit it, it passes an empty string instead of the value of the selected item. Is this because it's an ASP.Net script? I don't know a lot about ASP.Net, but I've never had this issue with PHP. Can someone explain how I would go about refreshing the dropdownlist without refreshing the entire page and still get the list to pass it's value upon form submission?
My javascript code on the page that opens the pop-up and reloads the list is below:
function openConsignorAdd() {
var url;
url = "/admin/consignor/csAdd.aspx";
window.open(url, "WizardWindow", "width=400,height=500,resizable=yes,scrollbars=yes");
}
function loadNewAdded(fn, cs_txt_id) {
// var pagePath = window.location.pathname;
var pagePath = "/admin/getNewList.asp";
var paramList = "data=";
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "?type=" + fn + "&cs_txt_id=" + cs_txt_id,
data: paramList,
success: function (data) {
//create jquery object from the response html
var $response = $(data);
//query the jq object for the values
var results = $response.filter('select#results').html();
if (fn == "consignor") {
$("select#<%=itemConsigner.ClientID%>").html(results);
} else if (fn == "cdr") {
$("select#<%=itemCDR.ClientID%>").html(results);
}
},
error: function () {
alert("Failed To Refresh!\n\nYou must manually refresh the page.");
}
});
}
My javascript code on the pop-up page to refresh the list is:
function refreshOpener(cs_txt_id) {
window.opener.loadNewAdded("consignor", cs_txt_id);
}
Those both work. And to get the value of my dropdownlist, I simply use:
if (itemConsigner.SelectedValue.ToString() != string.Empty)
{
itemCsTxtId = itemConsigner.SelectedValue.ToString();
}
with my dropdownlist being:
<asp:DropDownList ID="itemConsigner" runat="server" TabIndex="1"></asp:DropDownList>
If you need more info, just let me know. Any help is appreciated.
It seems that the issue is that since I am making the change after the page loads, the server does not see my new addition as one of the original options so ignores it completely. This is good so that people cannot just edit your forms I guess. So what I did was instead of getting the value of itemConsigner.SelectedValue, I grab the value for Request.Form["itemConsigner"] with the long ID. That way it doesn't validate that my submitted option was an original option.
Might be a silly observation but without all the code I'm not sure if this is the case. Are you just updating the original list with the id in the select options. The value needs to be populated as well for each. That could be why you are getting an empty value on after form submission.

jQuery UI autocomplete is not displaying results fetched via AJAX

I am trying to use the jQuery UI autocomplete feature in my web application. What I have set up is a page called SearchPreload.aspx. This page checks for a value (term) to come in along with another parameter. The page validates the values that are incoming, and then it pulls some data from the database and prints out a javascript array (ex: ["item1","item2"]) on the page. Code:
protected void Page_Load(object sender, EventArgs e)
{
string curVal;
string type ="";
if (Request.QueryString["term"] != null)
{
curVal = Request.QueryString["term"].ToString();
curVal = curVal.ToLower();
if (Request.QueryString["Type"] != null)
type = Request.QueryString["Type"].ToString();
SwitchType(type,curVal);
}
}
public string PreLoadStrings(List<string> PreLoadValues, string curVal)
{
StringBuilder sb = new StringBuilder();
if (PreLoadValues.Any())
{
sb.Append("[\"");
foreach (string str in PreLoadValues)
{
if (!string.IsNullOrEmpty(str))
{
if (str.ToLower().Contains(curVal))
sb.Append(str).Append("\",\"");
}
}
sb.Append("\"];");
Response.Write(sb.ToString());
return sb.ToString();
}
}
The db part is working fine and printing out the correct data on the screen of the page if I navigate to it via browser.
The jQuery ui autocomplete is written as follows:
$(".searchBox").autocomplete({
source: "SearchPreload.aspx?Type=rbChoice",
minLength: 1
});
Now if my understanding is correct, every time I type in the search box, it should act as a keypress and fire my source to limit the data correct? When I through a debug statement in SearchPreload.aspx code behind, it appears that the page is not being hit at all.
If I wrap the autocomplete function in a .keypress function, then I get into the search preload page but still I do not get any results. I just want to show the results under the search box just like the default functionality example on the jQuery website. What am I doing wrong?
autocomplete will NOT display suggestions if the JSON returned by the server is invalid. So copy the following URL (or the returned JSON data) and paste it on JSONLint. See if your JSON is valid.
http://yourwebsite.com/path/to/Searchpreload.aspx?Type=rbChoice&term=Something
PS: I do not see that you're calling the PreLoadStrings function. I hope this is normal.
A couple of things to check.
Make sure that the path to the page is correct. If you are at http://mysite.com/subfolder/PageWithAutoComplete.aspx, and your searchpreload.aspx page is in another directory such as http://mysite.com/anotherFolder/searchpreload.aspx the url that you are using as the source would be incorrect, it would need to be
source: "/anotherFolder/Searchpreload.aspx?Type=rbChoice"
One other thing that you could try is to make the method that you are calling a page method on the searchpreload.aspx page. Typically when working with javascript, I try to use page methods to handle ajax reqeusts and send back it's data. More on page methods can be found here: http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx
HTH.

recovering from missing session state in ASP.NET MVC with Telerik Ajax

I have a webpage which includes a telerik grid in ajax mode. The data for the grid is constructed in the controller action used to serve the view, and then stored in the session. 90% of the time its available to the ajax method used to populate the grid. And sometimes its not, which is odd. Some sort of race condition ?
public ActionResult EditImage(int productModelId, int revision)
{
ViewBag.Current = "Edit";
//Unit of work and repo generation removed from brevity
var modelToEdit = prodModelRepo.Where(p => p.ProductModelID == productModelId && p.Revision == revision).FirstOrDefault();
var vmie = new VMImageEdit(modelToEdit)
{
//init some other stuff
};
Session["vmie"] = vmie;
return View(vmie);
}
Now the telerik contorol will post back to _EISelect in order to populate its grid
// Ajax Actions for EditImage
[GridAction]
public ActionResult _EISelect()
{
var vmie = (VMImageEdit) Session["vmie"];
return View(new GridModel(vmie.Colours));
}
So if my session object is null, how can I recover - I guess I need the productModelId and Revision parameters from the original EditImage call. Are they available in the _EISelect in any way - its posted to, and the post contains nothing useful.
Oh to make this possibly harder, this page will be displayed via an inline frame.
The answer lies in the telerik ajax databinding - this can be used to pass arbitrary data in the querystring
.Select("_EISelect", "AdminProduct", new { productModelId = Model.ProductModelId, revision = Model.Revision})
which can be recovered in _EISelect as parameters. Simples.

Gridview manipulation using JQuery and JavaScript

I have an ASP.NET gridview I want to manipulate using JavaScript/JQuery. The problem I THINK I'm going to have with my approach is that the server won't have any knowledge of the rows that I am appending via gridview since the html representation of the gridview control is coupled with the object model that lives on the server. So here is what I need to do:
I need to append to the gridview when a user submits data, and submit each row in the batch of entered data to the server to be processed. Because I have other ASP.NET controls that will contain data that I want to submit, I'd like to submit all that data via a traditional postback to the server.
How do I implement this approach if possible?
If not possible, could you please explain?
Thank you very much for your help.
var queryString = "";
// This could be based on a number of different events
$('#finishButton').click(function(){
// Iterate through each input (you could add other form elements)
$('#myForm input').each(function(){
// Build your query string to post to your aspx page
queryString += $(this).attr("name") + "&" + $(this).val() + ",";
});
});
// Make sure special chars are escaped
queryString = escape(queryString);
// POST the form to your aspx page
$.ajax({
type: 'POST',
url: 'myFormProcessor.aspx',
data: queryString,
// Upon a successful POST, successHandler will be called
success: successHandler
});
// Add the new data to the grid
function successHandler(){
// Clone the last row
$('#myTable tr:last').clone(true).insertAfter('#myTable tr:last');
// Here you could just break apart the query
// string you build in the above code
// and use those values to change the values
// in the row you added to the grid
}
Make sure to unescape the query string in your aspx page, and then break it up by the delimiters you're using. I used '&' to separate key/value and commas between variables (inputs).

Resources