A long explanation but I believe this is a pretty simple question. I think I'm missing something here.
After selecting a user role from a dropdown menu I'm loading a partial view with users for that role into a DIV with ajax:
$.ajax({
type: 'post',
data: { id: roleId},
url: '#Url.Action("Manage","User")',
success: function (data) {
$("#user-manage").html(data);
}
});
Now, on the page I have a combobox with the list of users and a Delete button.
I highlight a user, press the Delete button and user gets deleted.
Great! It works ,however my problem is that the deleted user doesn't disappear from the Combobox list until the page is refreshed. And I can't refresh the page because that'd mean that web site user would have to start over with selecting the Role.
So, the question is how can I make the user disappear on the combobox as soon as I hit that delete button ?
Right now when the delete button is pressed the selected UserId is passed the following ajax call that deletes a selected user and returns the updated JSON user list:
function removeUser() {
var selectedUser = $("#user-combo").find(":selected").val(); //grab selected user
var selectedForRole = $("#role-id").val(); //hidden field to store selected role
$.ajax({
url:"/User/Delete", //Delete selected user and return updated Json list
data: { id: selectedUser , roleId: selectedForRole },
type: 'post',
success: function (data) {
var userList = $("#user-combo");
var listContent;
$.each(data, function (index, item) {
listContent += "<option value='" + item.Id + "'>" + item.Name + "</option>";
});
userList.html(listContent);
}
});
}
Functionally this works. The user gets deleted but I don't see it reflected on the $("#user-combo") box until I refresh the screen.
location.reload(); doesn't work for me as I don't want the web site user to go through selecting a role to see the updated list of users.
How can I make this interactive and users disappear when I delete them and appear when add them later on ?
Thank you in advance.
Edit.
Json object returned to the combobox:
return Json(roleUsers.Select(x => new
{
Id = x.Id,
Name = x.Name
}));
It is as simple as this:
$("#comboBox option[value='USER-NAME']").remove();
Put this in your removeUser(). function.
In fact the function must not olny remve the user from the remote list, but also from the DOM.
Hpe this help.
Check your callback function. Logic seems to be OK. I have just tested and replacing select's html will remove old items and add new ones. Here's a fiddle for that.
Add several console.log() calls in your success callback function. console.log(data); console.log(userList); console.log(listContent) and see if they contain the correct data... or whether they get executed at all.
For another possible cause check your roleUsers list on the server. It maybe contains the deleted user - i.e. if you pull it out from the cache and not from the database, or you do delete after the list load.
Related
I have a very simple scenario and I need advise as to the best way to achieve this in ASP.NET MVC.
I have two textboxes, one editable and the other readonly.
The second textbox is meant to display a calculated figure based on the a calculation done on the server and the value entered in TextBox one.
I am using DevExpress's suite, but I guess the concept should be the same. Does anyone have sample code or can elaborate the correct way to achieve this?
$(function(){
$("#textbox1_id).change(function(){
var value1=$(this).val();
$.ajax({
url:'/abc/xyz',
data:{myValue:value1},
type:'GET',
dataType:'json'
})success(function(data){
$("#textbox2").val(data.Value);
});
})
})
This sounds like a job for JQuery/Ajax.
You can set onChange event on your input box.
Through AJAX call to make a server side call to do the calculation and return the the results.
Then use JavaScript and JQuery to put the results in the non editable textbox.
$(document).ready(function () {
$("#InputID").onChange(function () {
$.ajax({
type: "POST",
url: "/MyController/CalculatorAction/" + $("#InputID").val(),
cache: false,
success: function (data) {
$("#ResultID").text(data);
}
});
ON the controller side you can set up a post action
public virtual ActionResult GetEquipmentNumberByInitials(string id){
var result = 0;
// do calculation
return Json(result)
}
I think it should be fairly simple, you just need to access the text property of the textbox in which you are entering the value , and then applying calculation on the off focus event of the textbox use this value to calculate the other value and put it inside the text property of the textbox.
Use the below link for refrence
https://www.devexpress.com/Support/Center/Question/Details/T114245
I'm very new to ASP.NET WebForms applications. I have an application using a DataGrid which has a DataBinding to a List of objects. When the page loaded completely, I want to add further information to each row in the DataGrid.
The process which determines the additional information for each row must run on the server side and takes about 2s per row (network access etc.). Therefore I would like my DataGrid to refresh after every row has been processed.
This means, that I want an asynchronous mechanism that loads the data while the web page is completely accessible for the user and updates the UI as soon as a row is processed on the server side.
Technically that means that I need to send a HTTP response after processing each row to the client. The client will then read the HTTP response and update the UI.
I already tried using a UpdatePanel with a ScriptManager according to this article.
The problem with this solution is, that the UI updates when the last row has been processed. This is too late. We need an UI update after each row.
I'm used to work with WPF desktop applications. In a WPF desktop application I would just use a background worker. In the ProgressReported-EventHandler I would update the Grid with the new information and invoke an IPropertyChanged notification.
How can I achieve that in ASP.NET (.NET 4.0)? Any help and web resources are highly appreciated.
You need to use an Ajax query and a WebService
place an import in your head tag
<script src="...../js/jquery.ajaxq-0.0.1.js" type="text/javascript"></script>
and place a script zone at the end of the apsx page
<script type="text/javascript">
$(document).ready(function () {
$('#<ID_GRID_NAME> tr').each(function () {
//Get customerId Key
var customerId = $(this).find("td:first").html();
if (customerId) {
$.ajaxq("interventionQ", {
type: 'GET',
dataType: 'json',
url: '<WEB_SERVICE_URL>' + customerId,
success: function (griddata) {
$(this).find("td:last").html('<span class="badge badge-important"></span>');
}
});
}
})
});
</script>
Get rid of the ScriptManager and use jQuery. Create a gridview and then you can grab that with your AJAX success method and append to an HTML table. You can create an empty table (and hide it) on the client side and then get your table rows via AJAX and append them to the table.
$.get( "Default.aspx/MethodName", obj, function ( response )
{
var content = $( $.parseHTML( response ) ).find("#divWhereYourGridviewIs");
if ( $( "#div table" ).html() == null ) {
$( "#divOnClient" ).html( content ); //this will be the first call to get the table
}
else {
var newRow = $( content ).find( "#grd tr" )[1]; //this will be for each additional row, the [1] skips the header and gets the first row.
$( "#htmlTable" ).append( newRow );
}
} );
If you have a choice between WebForms and MVC, it would be worth looking into MVC. This CoderProject page is part of a series which has useful information for doing all that you want to do and more. This page has links to some WebForms stuff.
Long story short, jQuery and jQueryUI have a lot of things like this and examples of how to do them.
I am working in ASP.NET MVC 3 and using Telerik. I have an empty telerik window. My goal is to only ask server for content when the user clicks a button, however I have no idea how this could be done. I imagine that to accomplish this I would need to store a reference to the telerik window in question. But how do i do this? plz help. This is how far I have got:
#{
Html.Telerik().Window()
.Name("ImportDialog")
.ClientEvents(events => events.OnOpen("DialogOpen"))
.Visible(false)
.Title("Import users")
.Draggable(false)
.Resizable(resizing => resizing.Enabled(false))
.Modal(true)
.Width(400)
.Height(400)
.Render();
}
I do want do do somethin in DialogOpen function, or alternatevly replace that client side function with a server side funciton....
You should use the client API of the Telerik Window and more specifically the ajaxRequest method.
So for example when the button is clicked you should get the client object and call the ajaxRequest method which will make the Window retrieve its content from that MVC action method.
e.g.
function DialogOpen(){
var myWin= $('#ImportDialog').data('tWindow');
myWin.ajaxRequest("Controller/Action", { name: "John",location:"Boston"});
}
I found one type of answer, however i am not sure yet if it is the best.
In the javascript function DialogOpen I send an ajax request to an url(also known as an Action of a Controller in MVC), the I put the result in the content of the dialog window, like so:
function DialogOpen ()
{
$.ajax({
type: "POST",
url: "Controller/Action",
data: "name=John&location=Boston",
success: function (htmlContent)
{
$('#ImportDialogContent').html(htmlContent);
},
error: function ()
{
$('#ImportDialogContent').html("<p>Could not import user data at this time</p>");
}
});
}
P.S.: I gave an ID to content area of telerik Window(ImportDialogContent)!
I have a textbox and a literal control on my page. Whenever a user enters search text in the textbox, the HTML code with the result gets generated behind the code and gets added to the literal control.
So, now I am trying to display search result as the user types in the textbox.
Can anyone tell me how i can achieve this?
You need to look no further than jQuery UI's autocomplete for remote data sources.
For a textbox like..
<input id="birds" />
You would need to do something like..
$( "#birds" ).autocomplete({ source: "search.php" });
The rest is all just tweaking according to your needs.
I think what you want is JQuery Autocomplete. You can find it HERE.
As I understand you want to emulate Google behavior.
In this case you need to send ajax request every time when user typed new symbol in your text and substitute html. But you will need change your Literal control to some 'div' or Panel because you can't find Literal control via Javascript. It's just substituted by a html content
ex:
$('#searchbox').keypress(function() {
$.ajax({
url: "search.html",
data: { q: $('#searchbox').val() },
cache: true,
success: function(html){
$("#results").html(html);
}
});
});
It's just a sample and probably needs some corrections. But idea in it.
Handling JSON data http://api.jquery.com/jQuery.getJSON/
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
I will start by telling I'm not an ASC/C# developer, this is for a homework. (i hope somebody will understand what i want :D, because i dont know exactly the terms)
I have Friends.aspx and Friends.aspx.cs
In Friends.aspx i have something like
<%# Reference Control="~/FriendBox.ascx" %>
<div class="controlcontainer clearfix friendlist_containeritems" id="divFriends" runat="server"> </div>
In Friends.aspx.cs i have this to populate divFriends:
foreach (FBUser user in list){
Control control = LoadControl("FriendBox.ascx");
FriendBox myControl = (FriendBox)control;
myControl.user = user;
divFriends.Controls.Add(myControl);
}
In my page a have a form, and divFriends is inside the form. I have a button in this form. If i just press the button, my page gets submitted and i can retrieve values from selected checkboxes. (Every control contains a checkbox)
Everithing worked fine until i tried to submit the page via Ajax (JQuery).
My problem is that even the checkboxes are on page (i can se them, select them), when i do an ajax submit i cannot access values from checkboxes.
This is the code i use to retrieve values from checkboxes:
foreach(Control ctrl in divFriends.Controls) {
var friendBox = ctrl as FriendBox;
//i can get here
if (friendBox != null)
{ //i never get here - because friendBox is allways null }
}
How can i make the content from divFriends accesible when i submit my form with Jquery?
Thanks in advance.
Edit: here is the javascript i use
$(document).ready(function () {
$('.big').click(function () {
//.big is my button
$('.big').attr('disabled', true);
var form_form = $(document).find('form');
$.ajax({
type: 'POST',
url: form_form.attr('action'),
data: form_form.serialize(),
dataType: 'json',
success: function (data) {
console.log('success');
},
complete: function (XMLHttpRequest, textStatus) {
$('.big').attr('disabled', false);
}
});
return false;
});
});
The javascript is working because i can submit data, and i can receive data back (json), when i look at the data submited i dont have the checkboxes from divFriends.
The problem appears to be asp.net state managment issue. You are only adding FriendBox one time (I'm assuming, probably with an if not page.ispostback sort of thign), and not on each page hit. Since FriendBox is added dynamically it's not surviving a postback and thus it does not exist when you try to read it.
You should add FriendBox each time the page loads, on Init before viewstate is loaded. Adding the controls during on init will allow Viewstate to track the values and will probably fix the issue.