Asp.net mvc passing a C# model to Javascript file - javascript

I want to pass the value i got it from model to the java-script function
<script type="text/javascript">
var checkin = #Model.Parameters.Checkin.ToString("dd-MM-yyyy");
var checkout = #Model.Parameters.Checkout.ToString("dd-MM-yyyy");
</script>
this function that i want to pass model chick-in and chick-out value to it:
$('document').ready(function () {
$("#Arrival").val(checkin);
$("#Departure").val(checkout);
});
i tried many solution but it didn't work yet .
any advice, thanks

if the #Model.Parameters.Checkin and #Model.Parameters.Checkout not null then Try:
<script type="text/javascript">
$( document ).ready(function(){
var checkin = '#Model.Parameters.Checkin.ToString("dd-MM-yyyy")';
var checkout = '#Model.Parameters.Checkout.ToString("dd-MM-yyyy")';
$("#Arrival").val(checkin);
$("#Departure").val(checkout);
});
Just you miss '. and also change $('document').ready(function () { }) to $(document).ready(function () { }).
you must write all script into a .cshtml file. #Model.Parameters.Checkin.ToString("dd-MM-yyyy") never work into a .js file.
Because, In .cshtml, when the the page is render then it white to HTTP response stream as a string.

In MVC, you can use following code:
<script type="text/javascript">
var number = parseInt(#ViewBag.Number); //Accessing the number from the ViewBag
alert("Number is: " + number);
var model = #Html.Raw(#ViewBag.FooObj); //Accessing the Json Object from ViewBag
alert("Text is: " + model.Text);
</script>

Related

How to pass a java ArrayList of Strings to JavaScript [duplicate]

I am using Thymeleaf as template engine. How I pass a variable from Spring model to JavaScript variable?
Spring-side:
#RequestMapping(value = "message", method = RequestMethod.GET)
public String messages(Model model) {
model.addAttribute("message", "hello");
return "index";
}
Client-side:
<script>
....
var m = ${message}; // not working
alert(m);
...
</script>
According to the official documentation:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[[${message}]]*/ 'default';
console.log(message);
/*]]>*/
</script>
Thymeleaf 3 now:
Display a constant:
<script th:inline="javascript">
var MY_URL = /*[[${T(com.xyz.constants.Fruits).cheery}]]*/ "";
</script>
Display a variable:
var message = [[${message}]];
Or in a comment to have a valid JavaScript code when you open your template file in a static manner (without executing it at a server).
Thymeleaf calls this: JavaScript natural templates
var message = /*[[${message}]]*/ "";
Thymeleaf will ignore everything we have written after the comment and before the semicolon.
More info: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining
var message =/*[[${message}]]*/ 'defaultanyvalue';
According to the documentation there are several ways to do the inlining.
The right way you must choose based on the situation.
1) Simply put the variable from server to javascript :
<script th:inline="javascript">
/*<![CDATA[*/
var message = [[${message}]];
alert(message);
/*]]>*/
</script>
2) Combine javascript variables with server side variables, e.g. you need to create link for requesting inside the javascript:
<script th:inline="javascript">
/*<![CDATA[*/
function sampleGetByJquery(v) {
/*[+
var url = [[#{/my/get/url(var1=${#httpServletRequest.getParameter('var1')})}]]
+ "&var2="+v;
+]*/
$("#myPanel").load(url, function() {});
}
/*]]>*/
</script>
The one situation I can't resolve - then I need to pass javascript variable inside the Java method calling inside the template (it's impossible I guess).
MAKE sure you have thymleaf on page already
//Use this in java
#Controller
#RequestMapping("/showingTymleafTextInJavaScript")
public String thankYou(Model model){
model.addAttribute("showTextFromJavaController","dummy text");
return "showingTymleafTextInJavaScript";
}
//thymleaf page javascript page
<script>
var showtext = "[[${showTextFromJavaController}]]";
console.log(showtext);
</script>
I've seen this kind of thing work in the wild:
<input type="button" th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'" />
If you use Thymeleaf 3:
<script th:inline="javascript">
var username = [[${session.user.name}]];
</script>
If you need to display your variable unescaped, use this format:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[(${message})]*/ 'default';
/*]]>*/
</script>
Note the [( brackets which wrap the variable.
Another way to do it is to create a dynamic javascript returned by a java controller like it is written here in the thymeleaf forum: http://forum.thymeleaf.org/Can-I-use-th-inline-for-a-separate-javascript-file-td4025766.html
One way to handle this is to create a dynamic javascript file with the
URLs embedded in it. Here are the steps (if you are using Spring MVC)
#RequestMapping(path = {"/dynamic.js"}, method = RequestMethod.GET, produces = "application/javascript")
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public String dynamicJS(HttpServletRequest request) {
return "Your javascript code....";
}
Assuming request attribute named "message":
request.setAttribute("message", "this is my message");
To read it in the html page using Thymeleaf template:
<script>
var message = "[[${message}]]";
alert(message);
</script>

how to use javascript variable into array in laravel blade file

How to use var aid value assign into $data array? I am getting error: "Use of undefined constant aid". I am working on Laravel 5.4. I want to show ($data['services'][aid]->servicesubdetails) value in tage. My code is below:
<script language="JavaScript">
function theFunction(e)
{
var aid= e.target.id;
$("p").html('{{ ($data['services'][aid]->servicesubdetails) }}');
}
</script>
Single quotes are interrupted by another single quote.
<script language="JavaScript">
function theFunction(e)
{
var aid= e.target.id;
$("p").html(“{{ ($data['services'][aid]->servicesubdetails) }}”);
}
</script>
Notice “ instead of ‘.
EDIT
You can use json to use you PHP array in javascript
Look at LaravelDisplayData and PHPJsonEncode
<script language="JavaScript">
var data = #json($data)
function theFunction(e)
{
var aid= e.target.id;
$("p").html(data.services[aid].servicesubdetails);
}
</script>

Passing a parameter to my Knockout ViewModel

I have an MVC site that uses Knockout JS. Basically, the MVC handles routing to a few different pages, and each page has a viewmodel.
One of the pages requires a parameter to filter the data. The code for the MVC Controller for that page is as follows:
public ActionResult Transactions(int policyId)
{
ViewData["policyId"] = policyId;
return View();
}
The View for that page includes a hidden field.
<input type="hidden" name="hldPolicy" value="#ViewData["policyId"]">
Then after the html for the page,
#section scripts
{
#Scripts.Render("~/bundles/myBundle")
<script>
$(document).ready(function () {
var policyId = $('#hldPolicy').val();
var transactionViewModel = new TransactionViewModel(policyId);
ko.applyBindings(transactionViewModel);
});
</script>
}
The problem is this doesn't work because the hidden field is undefined when the script runs. That doesn't make sense to me as I thought that was what the $(document).ready was protecting against. What am I doing wrong here? And is there a better way to pass a parameter from the URL params into the viewmodel?
You can use it like this. Here you dont actually have to pass the parameter instead define a function which will be called on viewmodel initialization and get the data according to your requirements.
#section scripts
{
#Scripts.Render("~/bundles/myBundle")
<script type="text/javascript">
function TransactionViewModel(){
var self = this
self.SomeProperty = ko.observable()
self.LoadData = function(){
var policyId = $('#hldPolicy').val();
self.SomeProperty(policyId)
}
self.LoadData()
}
$(document).ready(function () {
ko.applyBindings(new TransactionViewModel());
});
</script>
}
When knockout model will be initialized it will call self.LoadData() automatically.
EDIT
I found you are missing id attribute at your input
<input type="hidden" id="hldPolicy" name="hldPolicy" value="#ViewData["policyId"]">
Now it should work properly.
EDIT:
You can also do it like this
#section scripts
{
#Scripts.Render("~/bundles/myBundle")
<script type="text/javascript">
function TransactionViewModel(policyId){
var self = this
self.SomeProperty = ko.observable()
self.LoadData = function(policyId){
self.SomeProperty(policyId)
}
self.LoadData(policyId);
}
$(document).ready(function () {
var policyId = $('#hldPolicy').val();
ko.applyBindings(new TransactionViewModel(policyId));
});
</script>
}

SharePoint 2013 get list item field value

I have a document library where I added a text column Read. I'm using a script editor web part to insert some JavaScript. I need to get the value of this column Read for a specific item (I know the item Id).
I would appreciate any help. Thank you!
This code worked:
this.oListItem = oList.getItemById(itemid);
ctx.load(this.oListItem);
ctx.executeQueryAsync(Function.createDelegate(this,
function () {prevText = this.oListItem.get_item('Read'); }),
function (sender, args) { alert('Error occured' + args.get_message());
});
You should use Sharepoint client object model to get the document library where you added the text column. After that you can get the list item by building a caml query with the item id and you can get the value of your column.
You may want to use SPServices or SharepointPlus to help you. With SharepointPlus the code would be:
$SP().list("Name of your list").get({fields:"Read",where:"ID = 123"}, function(data) {
if (data.length===1) alert("Read = "+data[0].getAttribute("Read"))
else alert("Unable to find ID 123")
})
Using SPServices and jQuery, you can reference those in your code:
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="jquery.SPServices.min.js"></script>
Then get the fields of the current item using this code:
<script type="text/javascript">
$(document).ready(function() {
// Don't forget to replace the document library's name
// if it's not "Documents"...
getListItems('Documents',
function(items){
var e = items.getEnumerator();
while (e.moveNext()) {
var item = e.get_current();
//console.log(item.get_item('FileLeafRef')); //print File or Folder Name
//console.log(item.get_item('FileRef')); //print File or Folder Url
var read = item.get_item('Read');
alert('Read = ' + read);
}
},
function(sender,args){
console.log(args.get_message());
}
);
});
function getListItems(listTitle,success,error)
{
//alert('getting items');
var context = SP.ClientContext.get_current();
var list = context.get_web().get_lists().getByTitle(listTitle);
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
context.load(items);
context.executeQueryAsync(
function() {
success(items);
},
error
);
}
</script>

Retrieve a hiddenfield value through javascript

I am using the following javascript to retrieve a value of a asp hidenfield.
var pagemode
function setValue() {
pagemode= document.getElementById('<%#litTest.ClientID%>').value;
}
function Item_load(sender, eventArgs) {
window.location.href = "Request.aspx?Request_ID=" + eventArgs.get_item().getMember('Request_ID').get_value() + "&ListType=" + pagemode;
}
The value to the hiddenfield is loaded in page load in code behind. I need to pass the value as a querystring and it comes as undefined.
I would really appreciate if anyone can help.
So you don't get a reference to your hiddenfield? Try this:
<script type="text/javascript">
var litTestID = '<%= litTest.ClientID %>';
function setValue() {
var pagemode = $(litTestID).value;
// ...
}
</script>
Otherwise use the javascript debugger to inspect the order of executino and the variable values.

Categories

Resources