How do I access methods when using a jquery script? - c#

I have a Jquery Script and whenever a drop-downlist value changes, it is supposed to take the value and pass it into a method that gets the value and calculates a price based on the value and then in the end sets a label to the new value.
Here is my Jquery Script:
#section PageScripts{
<script type="text/javascript">
$(document).ready(function () {
$('#paperTypeJList').change(function () {
// trying to figure out how to pass the value to the following method
});
});
</script>
}
Here is my method that I'm trying to call inside of the Jquery Script:
public decimal getNewPrice(string dropdownValue)
{
// do something with value and return a decimal
return 0;
}

You have to send ajax call using jquery to server.
Something like this:
<script type="text/javascript">
$(document).ready(function () {
$('#paperTypeJList').change(function () {
// trying to figure out how to pass the value to the following method
var value = $(this).val();
$.ajax({
url: '#Url.Action("Action","Controller")',
data: {dropdownValue:value},
cache: false,
success: function(response){
alert(response);
}
});
});
});
</script>

Try this using jquery Ajax
Html :
<label id="priceLabel"></label>
Javascript
$(document).ready(function () {
$('#paperTypeJList').change(function () {
$.ajax({
type: "GET",
url: "/Home/getNewPrice?dropdownValue=" + this.value,
async: true,
success: function (result) {
document.getElementById('priceLabel').innerHTML = result;
}
});
});
});
Controller
public decimal getNewPrice(string dropdownValue)
{
// do something with value and return a decimal
return 5.72M;
}

$(document).ready(function () {
$('#paperTypeJList').change(function () {
getNewPrice($(this).val());
});
});

My current code is below:
#section PageScripts{
<script type="text/javascript">
$(document).ready(function () {
$('#paperTypeJList').change(function () {
$.ajax({
type: "GET",
url: "/Home/getNewPrice?dropdownValue=" + this.value,
async: true,
success: function (result) {
document.getElementById('priceLabel').innerHTML = result;
}
});
});
});
</script>
}
public decimal getNewPrice(string dropdownValue)
{
// do something with value and return a decimal
return 5.72M;
}

Related

Knockout ViewModel Update

I am new to Knockout and I am trying to update my ViewModel from an ajax call. This is what I have right now:
LoanDeductions.js
var deductionLine = function (deductionID, deductionName, amount) {
self = this;
self.deductionID = ko.observable(deductionID);
self.deductionName = ko.observable(deductionName);
self.amount = ko.observable(amount);
};
function LoanDeductions(deductions) {
var self = this;
self.loanDeductions = ko.observableArray(ko.utils.arrayMap(deductions, function (deduction) {
return new deductionLine(deduction.deductionID, deduction.deductionName, deduction.amount)
}));
// Operationss
self.removeLine = function (line) { self.loanDeductions.remove(line) };
};
and this is my scripts in my view:
#section scripts
{
<script src="~/Scripts/koModel/LoanDeductions.js"></script>
<script type="text/javascript">
var updateValues = function () {
$.ajax({
'url': '#Url.Action("UpdateDeductionValues","LoanApp")',
'data': { amount: $('.LoanAmount').val() },
'success': function (result) {// update viewmodel scripts here}
});
var viewModel = new LoanDeductions(#Html.Raw(Model.CRefLoansDeductions2.ToJson()));
$(document).ready(function () {
ko.applyBindings(viewModel);
$('.datepicker').datepicker();
$('.LoanAmount').change(function () {
updateValues();
};
});
});
</script>
}
So, in my view, I have a dropdown list with class name "LoanAmount" which when value is changed, it will perform an ajax call, send the selected loanAmount value to the server, recompute the deduction amounts, then the server returns a jsonresult that looks like this:
"[{\"deductionID\":1,\"deductionName\":\"Loan Redemption Fee\",\"amount\":53.10},{\"deductionID\":2,\"deductionName\":\"Document Stamp\",\"amount\":9.00}]"
Now what I wanted to do is use this json data as my new viewModel.
Can anyone show me the way how to do this, please note that I manually mapped my viewmodel and didn't used the ko mapping plugin.
Any help will be greatly appreciated. Thank you, more power!
EDIT (in response to Fabio)
function updateData() {
$.ajax({
url: '#Url.Action("UpdateDeductionValues","LoanApp")',
data: { amount: self.selectedLoanAmount() },
success: function (deductions) {
//load your array with ko.utils.arrayMap
ko.utils.arrayMap(deductions, function (deduction) {
return new deductionLine(deduction.deductionID, deduction.deductionName, deduction.amount)
});
}
});
}
Not sure If I understood your problem, but if you want to change model values outside of the class, you need to do something like this:
$(document).ready(function () {
var viewModel = new LoanDeductions(#Html.Raw(Model.CRefLoansDeductions2.ToJson()));
ko.applyBindings(viewModel);
$('.datepicker').datepicker();
function updateValues() {
//do you ajax call
//update the model using viewModel.loanDeductions(newItens);
};
$('.LoanAmount').change(function () {
updateValues();
};
});
EDIT 1 - Just to show how to use knockout without jquery.change
function LoadDeductions() {
//declare you properties
var self = this;
self.loanAmount = ko.observable('initialvalueofloanamount');
self.loanDeductions = ko.observableArray();
//create a function to update you observablearray
function updateData() {
$.ajax({
url: '#Url.Content('yourActionhere')' or '#Url.Action('a', 'b')',
data: { amount: self.loadAmount() },
success: function (deductions) {
//load your array with ko.utils.arrayMap
}
});
}
//everytime that loanAmount changes, update the array
self.loanAmount.subscribe(function () {
updateData();
});
//update values initializing
updateData();
};
$(function() {
ko.applyBindings(new LoadDeductions());
});
Bind the select in the HTML
<select data-bind="value: loanAmount"></select>
EDIT 2 - To your second problem
function updateData() {
$.ajax({
url: '/LoanApp/UpdateDeductionValues', //try to write the url like this
data: { amount: self.selectedLoanAmount() },
success: function (deductions) {
//load your array with ko.utils.arrayMap
self.loanDeductions(ko.utils.arrayMap(deductions, function (deduction) {
return new deductionLine(deduction.deductionID, deduction.deductionName, deduction.amount)
}));
}
});
}
Your success handler should look like this.
function(result){
self.loanDeductions(result);
}
Unless you are trying to append in which case it would be
self.loanDeductions(self.loanDeductions().concat(result));

Ajax call Parameter does not accept #Model as parameter value

I have following code which is making an Ajax call from a .CSHTML file.
<script type="text/javascript">
$("#Save").click(function () {
var model = {
EmployeeId: #Model.EmployeeId,
OverrideTermDate: $('#OverrideTermDate').val(),
OverrideHireDate: $('#OverrideHireDate').val(),
};
$.ajax({
data: #Model.EmployeeId,
url: "/Employee/UpdateOverrideDates",
type: "POST",
success: function (result) {
$(function () {
$("#dialog").dialog();
});
}
});
});
</script>
My VS shows syntax error. But instead of #Model.EmployeeId if I hardcode it to any int value like 1 then it works fine.
Now #Model.EmployeeId is not NULL and it is an int. It is just that Ajax does not like it. Any idea why? Should I not be using #Razor components in Ajax calls?
To use Razor in JS, wrap the attributes in '',
data : '#Model.EmployeeId',
//For passing integer use parseInt('#Model.EmployeeId') or Number('#Model.EmployeeId')
and
var model = {
EmployeeId: '#Model.EmployeeId',
....
};
The quotes act as delimiters, so the Razor parser recognizes the values.
or Alternatively,
data : #Model.EmployeeId + "",
It's just a bug in Visual Studio, the view should works as excepted.
The answer was explained here: Razor/JavaScript and trailing semicolon.
If you don't like it, you can just put the "plus zero" after the #Model
$("#Save").click(function () {
var model = {
EmployeeId: #Model.EmployeeId + 0,
OverrideTermDate: $('#OverrideTermDate').val(),
OverrideHireDate: $('#OverrideHireDate').val(),
};
$.ajax({
data: #Model.EmployeeId + 0,
url: "/Employee/UpdateOverrideDates",
type: "POST",
success: function (result) {
$(function () {
$("#dialog").dialog();
});
}
});
});

Jquery ajax call is not working.. Please provide me the solution

//When focusout event is working, tested with alert.. but ajax call is not working and my aspx.cs method also not firing.. Please solve this issue.
//This is my aspx page jquery code.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var elem = document.getElementById('<%=txtProduct.ClientID %>');
$(elem).focusout(function () {
myF($(this).val());
});
function myF(value) {
var fist = value.split(' ( ', 1);
$.ajax({
type: 'POST',
url: 'Invoice.aspx/getProductDetails',
data: "{'strCode':'" + fist + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert(response.d.toString());
},
failure: function (response) {
alert('error');
}
});
}
});
</script>
//Server side code
[WebMethod]
public static string getProductDetails(string strCode)
{
List<string> companyInfo = new List<string>();
companyInfo.Add(HttpContext.Current.Cache[Convert.ToString(HttpContext.Current.Session["UserID"]) + "CompanyID"].ToString());
companyInfo.Add(strCode);
List<string> price = Database.MasterDB.getProductInfo(companyInfo);
if (price.Count > 0)
return price[0].ToString();
else
return "000";
}
Since you are using Session thing inside web method, that might be giving null values or blank values. This is because you have not enabled session for webmethod.
Like this - [WebMethod(EnableSession=true)].
Read more

JSON TinyMCE return value "\t"

Should I use another variable for "streszczenie"? or what should I do?
In my opinion in TinyMCE body have html but I get only "\t" Pobably I have got problem with JS
this is new problem - this question is related with this link. I added this for other users
this I write in TinyMCE
this I get from TinyMCE textarea "streszczenie"
As you can see there is text ghhfgh but I can`t get this text
Now I have got problem with execute JSON
<script type="text/javascript">
function Save() {
tinyMCE.triggerSave();
var Temat_controll = $('#Temat').val();
var Streszczenie_controll = tinyMCE.get('Streszczenie').getContent();
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function() {
},
success: function(data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
I get this but all the time JSON is not execute
When I click button tinyMCE.get('Streszczenie').getContent() is empty I check this and I don`t know why because I have got text into textarea
<script type="text/javascript">
function Save() {
var Temat_controll = $('#Temat').val();
var $d = tinyMCE.get('Streszczenie').getContent();
if ($d.length != 0) {
if ($d.val().length != 0) {
var Streszczenie_controll = tinyMCE.get('Streszczenie').getContent();
}
else {
var Streszczenie_controll = 'ewewe';
}
}
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
You are getting the content in wrong way, not by jQuery's val().
To get the tinymce content, just use tinyMCE object reference:
// Get the HTML contents of the currently active editor
console.debug(tinyMCE.activeEditor.getContent());
// Get the raw contents of the currently active editor
tinyMCE.activeEditor.getContent({format : 'raw'});
// Get content of a specific editor:
tinyMCE.get('content id').getContent()
As mentioned:
http://www.tinymce.com/wiki.php/API3:method.tinymce.Editor.getContent
Hope it heled. Polish man : )

JQuery Autocomplete loading data from model in aspx page

I am trying to
1) create a JQuery AutoComplete box that is populated from an aspx method, and
2)once I get the results, I wish to populate these results inside a list.
At the moment I am trying to do step one however without my success.
My code is as follows:-
ASPX
<script>
$(function () {
$("#persons").autocomplete({
//source: availableTags
source: function (request, response) {
var term = request.term;
var personArray = new Array();
$.post('JQAutoComplete.aspx/FetchPersonList', { personName: term }, function (persons) {
personArray = persons;
alert('PersonArray' - personArray);
alert('Persons' - persons);
response(personArray);
});
}
});
});
<div class="ui-widget">
<label for="persons">Persons: </label>
<input id="persons" />
</div>
</body>
and my aspx.cs is as follows :-
public JsonResult FetchPersonList(string personName)
{
var persons = ctx.GetDataFromXML(false, 0);
return (persons) as JsonResult;
}
*************UPDATE ASPX.CS*******************
ok so I changed the method to this:-
[WebMethod]
public static List<Person> FetchPersonList()
{
//var persons = this.HouseService.SelectByName(houseName).Select(e => new String(e.Name.ToCharArray())).ToArray();
var persons = ctx.GetDataFromXML(false, 0);
return (List<Person>) persons;
}
but I am still not getting through the method!
However the code is not hitting this method at all.
How can I get this list?
Thanks for your help and time
Ok I found the problem.
I changed my JQuery to the following and its calling the method now :-
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#persons").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "JQAutoComplete2.aspx/FetchPersons",
data: "{'name':'" + document.getElementById('persons').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
alert(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
and my ASPX.CS looks like this :-
[WebMethod]
public static List<Person> FetchPersons(string name)
{
var persons = ctx.GetDataFromXML(false, 0);
return (List<Person>)persons;
}

Categories