How to implement calculated fields based on text input from another TextBox? - c#

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

Related

MVC 4 C# Calendar Widget from Action-View

I have created a web calendar using HTML,CSS and C# in an MVC application. The HTML is in a view and I have a controller with an action that initializes the Calendar and displays the correct days on the view.
It works as intended but the problem comes from the fact that I want to embed this calendar to a couple of pages in unrelated Views controlled by different actions and with different models loaded.
I could copy paste the view code and make the necessary adjustments to the model but that would not be ideal. I tried with RenderAction but the problem is that when I use the buttons to navigate to different months I leave the initial view. e.g.:
#Html.ActionLink("‹", "Calendar",
new { month = Model.RequestedDateTime.Month - 1, year =
Model.RequestedDateTime.Year })
Is there a way to modify this behavior?
Thanks
Html.ActionLink, alway creates a normal link, with have the common behaviour. If you want to share your calender.
To avoid redundant code, you may redesign the calender as a partial view and replace the link by a label for example. Bind an ajax function to the label-click-event to refresh the calender. Something like:
#Html.Label("<", new { onclick="pageMonthBack("+Model.RequestedDateTime.Month - 1+", " Model.RequestedDateTime.Year+");" })
I would place the called ajax functions in a script which is loaded separately.
I solved the problem in a similar way, to what developer10214 proposed. I used a div and in that I used Render.Action. Then I used the following code
$(function () {
$("#cal").on('click', "#backwards", function () {
$.ajax({
url: "Home/Calendar?target=backwards",
cache:false,
type: "GET",
success: function (result) {
$("#cal").html(result);
}
});
});
});
in the including page. And I did not use ActionLink at all.

Lazy loading Telerik window content

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)!

Display search result as you type in ASP.NET

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');
});

Asp.net retrieve content from a Control

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.

How to Customize Hyperlinks on Client Side in ASP.NET MVC

I need to be able to do two things with Javascript or JQuery, without involving third-party open source libraries:
Use a jQuery or Javascript function to fill the HREF attribute of a link.
Perform an HTTP Get or Post operation OnUpdate of a text box or combo box (using the above javascript function to specify the HTTP target)
The end result will be hyperlinks posted to the controller that look similar to this:
http://mydomain/addresses/1?order=name&state=ca
The controller will return a new page, ordered by name and filtered on the state of California.
Suggestions?
If you have 2 textboxes and a hyperlink with url, try something like:
$(document).ready(function() {
$('a#yourHyperLinkId').click(function(event) {
event.preventDefault();
var url = $(this).attr('href');
var order = $('input#order').val();
var state = $('input#state').val();
$.get(url, { order: order, state: state }, function(response) {
$('div#yourDivForResponse').html(response);
});
});
});
I am not sure I follow...
Why do you need to fill the HREF of the link if your going to use JQuery to do the postback anyway?
Some elements of answer here : Passing Javascript variable to <a href >
If you want to load the controller response in the window, you can use a form with a crafted action. If not, you can either use an iframe as a target to the form or use an XHR object. Whatever solution you choose, you will link it to the onchange event of the text box or combo box.
Thanks fellas for pointing me in the right direction.
Answer to #1:
document.getElementById("link2").setAttribute("href",strLink);
Answer to #2 (more or less):
$("#mySelect").change(function() {
document.location = this.value;
});

Categories