how to get property from code behind jquery variable? - c#

I want to retrieve property value in jquery function and want to set it in variable. I am trying with below code but its not working.
.cs file
private string _Heading;
public string Heading { get { return _Heading; } set { _Heading = value; } }
.aspx
<script type="text/javascript">
$(document).ready(function () {
$("#btnShowSimple").click(function (e) {
ShowDialog(false);
e.preventDefault();
var someProp = "<%= this._Heading; %>";
alert(someProp);
});
</script>
What should i do to retrieve property value?? Anyone have solution than please help me in this.

Firstly, if the variable is private you will not be able to access it in your JavaScript so you should use the public Heading property instead.
Secondly, you have a semi colon in your JavaScript which needs to be removed so change this line
var someProp = "<%= this._Heading; %>";
To this
var someProp = "<%=this.Heading%>";

Related

viewmodel parameter into json for ajax request

In my Net Core 2.1 MVC project I have a viewmodel parameter userID, that I want to assign to a JQuery variable after the page loads. The ID is not displayed anywhere on the page.
So far, this doesn't seem to work:
View:
#{int userID = Model.ID;}
// rest of html page.
#section scripts {
<script src="~/AssigntoVariable.js"></script>
}
AssignToVariable.js
$(document).ready(function () {
$(function () {
var json = userID;
console.log(json);
// removed further code
When I run this, I receive a 'UserID not defined' error, obviously.
How can I put the userID parameter from my viewmodel directly in a JQuery script?
You can access viewmodel parameter ID as userID on client-side like:
#section scripts {
<script type="text/javascript">
var userID = #(Html.Raw(Json.Encode(Model.ID)));
// You can now access userID here
console.log(userID);
</script>
<script src="~/AssigntoVariable.js"></script>
}
and now you can also access userID in AssignToVariable.js like:
$(document).ready(function () {
var json = userID;
console.log(json);
});
Please note that you don't need to use
$(document).ready(function () {
$(function () {
both of them in AssignToVariable.js file, as $(function () { is just a shorthand for $(document).ready(function () {. Please use either one of them.

How To Use ViewBag Data In jQuery

Here I have ViewBag in a controller which contains text i.e ViewBag.Msg = "No Sprint".
And I am trying to use ViewBag.Msg in Jquery to display modal.
Now, the problem is that the script is script never gets executed.
Below is my jQuery.
<script>
$(document).ready(function () {
debugger;
if (#ViewBag.Msg != null)
{
$("#myModal").modal();
}
});
</script>
Any help will be highly appreciated. Thank You.
You need to use quotation marks for the view bag, as it will appear as a literal string.
If your debugger is not hitting at all, then you have another issue, post your full code. (your .cshtml file and layout)
<script>
$(document).ready(function () {
debugger;
if ('#ViewBag.Msg' != null)
{
$("#myModal").modal();
}
});
</script>
Please use the below code.
<script>
$(document).ready(function () {
debugger;
var msg='#ViewBag.Msg';
if (msg !== '')
{
$("#myModal").modal();
}
});
</script>

Getting a framework to deal with knockout.js not persisting via hidden field

VS2013, WebForms, .NET 4.51
I want to use a hidden field to maintain the contents of my Knock Out view model across postbacks. So I took the KO code from http://knockoutjs.com/examples/cartEditor.html and then read http://www.codeproject.com/Articles/153735/Using-KnockoutJS-in-your-ASP-NET-applications for some ideas.
The end result is the following:
<asp:HiddenField ID="HiddenField1" runat="server" />
<script type='text/javascript' src="http://knockoutjs.com/examples/resources/sampleProductCategories.js"></script>
<script type="text/javascript">
function formatCurrency(value) {
return "$" + value.toFixed(2);
}
var CartLine = function () {
var self = this;
self.category = ko.observable();
self.product = ko.observable();
self.quantity = ko.observable(1);
self.subtotal = ko.computed(function () {
return self.product() ? self.product().price * parseInt("0" + self.quantity(), 10) : 0;
});
// Whenever the category changes, reset the product selection
self.category.subscribe(function () {
self.product(undefined);
});
};
var Cart = function () {
// Stores an array of lines, and from these, can work out the grandTotal
var self = this;
self.lines = ko.observableArray([new CartLine()]); // Put one line in by default
self.grandTotal = ko.computed(function () {
var total = 0;
$.each(self.lines(), function () { total += this.subtotal() })
return total;
});
// Operations
self.addLine = function() {
self.lines.push(new CartLine());
SaveList();
};
self.removeLine = function(line) {
self.lines.remove(line);
SaveList();
};
self.save = function () {
var dataToSave = $.map(self.lines(), function (line) {
return line.product() ? {
productName: line.product().name,
quantity: line.quantity()
} : undefined
});
alert("Could now send this to server: " + JSON.stringify(dataToSave));
};
self.SaveList = function () {
var myHidden = document.getElementById('<%= HiddenField1.ClientID %>');
if (myHidden)//checking whether it is found on DOM, but not necessary
{
var dataToSave = $.map(self.lines(), function (line) {
return line.product() ? {
productName: line.product().name,
quantity: line.quantity()
} : undefined;
});
alert("Saving - " + JSON.stringify(dataToSave));
myHidden.value = JSON.stringify(dataToSave);
}
};
};
var stringViewModel = document.getElementById('<%=HiddenField1.ClientID %>').value;
var viewModel;
if (document.getElementById('<%=HiddenField1.ClientID %>').value == '') {
alert('Nothing In Hidden Field');
viewModel = new Cart();
} else {
viewModel = ko.utils.parseJson(stringViewModel);
for (var propertyName in viewModel) {
viewModel[propertyName] = ko.observable(viewModel[propertyName]);
}
}
ko.applyBindings(viewModel);
$(document.forms[0]).submit(function () {
alert('In Submit');
viewModel.SaveList();
});
</script>
So basically when the page loads we create a new instance of the Cart. And when the form is posted we successfully have the cart serialized to HiddenField1 and I can see the expected value in the code behind:
protected void btnSave_OnClick(object aSender, EventArgs aE)
{
if (HiddenField1.Value == null)
{
}
}
however after the postback the contents of stringViewModel
var stringViewModel = document.getElementById('<%=HiddenField1.ClientID %>').value;
is always blanl / empty? Why is that?
And then assuming I have the correct JSON is the following the correct way to apply it back to the view model?
viewModel = ko.utils.parseJson(stringViewModel);
for (var propertyName in viewModel) {
viewModel[propertyName] = ko.observable(viewModel[propertyName]);
}
EDIT: I tried a few things with no luck
Added all JS code to jQuert OnReady() handler
Tried using instead of ASP:HiddenField
In all cases in PostBack I can see the value assigned to the hidden field by SaveList(), but when the page is displayed again (after postback) the value of the hidden field is an empty string
For the first part, what you're doing is correct. Use the console (press F12 in your browser) to examine the hidden field, and check if it has the value. If you see it in the server side, it should be in the client side. You can also run js code, and set breakpoints to discover what the problem is. You can also add a PreRender handler in the server side, and add a breakpoint and debug to check that the Value has not been deleted in the server side (this event happens just before the page is rendered to be sent to the browser).
For the second part, the fastest way to do what you need is to use knockout mapping, which creates a model from a JavaScript object, or from JSON. You need to use this: ko.mapping.fromJSON. This will create a new viewmodel, which you can directly bind, from your JSON. (As you can read in the docs, you can customize how the view model is created).
However, what you're doing is quite strange. You normally use Knockout with Web API, or Web Services, or Page methods, without reloading the page. The model is recovered, and updated, changed, etc. through one of those technologies, using AJAX.

JQuery get value from .resx file

When I change my dropdown list, I want change a label (lblCustomer).
I don't know how to get value from resource file.Any ideas!?
.text('"<%$ Resources:lblCustomer%>"'); this not work. 10x
$(function () {
$('#<%= ddlCustomer.ClientID %>').change(function ()
{
$('#<%= lblCustomer.ClientID %>').text('"<%$ Resources:lblCustomer%>"');
})
}
);
I had similar problem to this. What I end up doing is registering a startup script that reads the values from the .resx file into a variable in javascript. Then I just reference the javascript variables as I need to.
C# Code:
StringBuilder colModel = new StringBuilder();
colModel.AppendFormat("var uiStrings = {{ captureStart: \"{7}\", captureOK: \"{0}\", captureRegister: \"{1}\", captureBad: \"{2}\", captureRegisterBad: \"{8}\", gridTitle: \"{3}\", gridIsCap: \"{4}\", gridNoCap: \"{5}\", gridDelete: \"{6}\", captureDiffUser: \"{9}\" }};",
this.GetLocalResourceObject("capOK").ToString(), this.GetLocalResourceObject("capRegisterOK").ToString(), this.GetLocalResourceObject("capBad").ToString(),
this.GetLocalResourceObject("gvCaption").ToString(), this.GetLocalResourceObject("gvIsCaptured").ToString(), this.GetLocalResourceObject("gvIsNotCaptured").ToString(),
this.GetLocalResourceObject("gvDelete").ToString(), this.GetLocalResourceObject("capStart").ToString(), this.GetLocalResourceObject("capRegisterBad").ToString(),
this.GetLocalResourceObject("capDiffUser").ToString());
ClientScript.RegisterStartupScript(this.GetType(), "initData", colModel.ToString(), true);
JavaScript:
$("#status").html(uiStrings.captureDiffUser);
Hope this helps!
You can use the GetGolabalRessourceObject Function.
$(function () {
$('#<%= ddlCustomer.ClientID %>').change(function ()
{
$('#<%=lblCustomer.ClientID%>').text('<%=GetGlobalResourceObject("lblCustomer")%>');
})
}
);

Assigning C# variable value using javascript variable in code behind

I am trying to access the script variable pic and assign it to another variable in C#, say hidden field hdn. The script below is also placed on the same code behind page for some reason. I can directly access the hidden field here. But how do I assign it value from the script variable?
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
alert(pic);
});
});
});
</script>
There is no way to assign a C# variable by javascript.
You have to send that value from the client (where you JavaScript is running) to the Server, and assign it.
This is so called ajax request, just google it and you'll find millions of good examples of how to achieve that.
create a hidden filed and then set the value from javascript
<asp:hiddenfield id="hf_MyValue"
value="whatever"
runat="server"/>
How To Set value in javascript
//get value from hidden filed
var test= document.getElementById('<%= hf_MyValue.ClientID %>');
//set value in hidden filed
document.getElementById('<%= hfBrand.ClientID %>').value = "True";
Create a hidden variable like this,
<input type="hidden" id="hdnVariable" runat="server" />
Now try this code
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
//assign value to server side hidden variable
$("#<%=hdnVariable.ClientID%>").val(pic);
});
});
});
</script>
Now you can access this hidden field from C# code like this
string pic=hdnVariable.Value;

Categories