Is there a way to use javaScript syntax inside Html helper - javascript

I have the following code inside my razor view:-
#Html.PagedListPager(Model , page => Url.Action("Index","Server", new
{
searchTerm = ViewBag.searchTerm,
page,
sort = ViewBag.CurrentSortOrder,
pagesize = $("#pagesize").val()
}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(PagedListRenderOptions.ClassicPlusFirstAndLast,
new AjaxOptions
{
UpdateTargetId = "ServerTable" ,
LoadingElementId="progress2"
}))
But i am unable to get the value of field using the following $("#pagesize").val(), so can anyone adivce if i can use a javaScript like syntax inside an Html helper ?
Thanks

The answer is : NO WAY!
Because:
You cannot pass anything from javascript to razor without going through the server.
That is because the razor is executed server side (hence the c# in it). The controller is called, that class is instantiated, then the method is invoked which matches the action requested, and then a view is returned. When the view is returned, the c# code in the view is executed. Once all code has been executed, it issues the html page in the response and then the javascript runs on the client. For you to get from javascript to razor, you would have to issue a new request to go through that path from the beginning in order to come back out in the end.
Solve this issue server side.
More detailed information please see this link:
Pass js variable or inout value to razor

Related

in Rails, How to make a query in javascript?

Given the id of an element I need to make a query in javascript, for example:
javascript:
var post_value = $(".post").val() # return a post ID;
var post = #{Post.find_by(id: post_value).to_json.html_safe};
But the post_value variable don't recognize it
If I manually pass a value to it, it recognizes it and asks me the query of the post, for example:
var post = #{Post.find_by(id: 181).to_json.html_safe}; # If work because I pass 181 as an ID value
I would be very grateful if you could help me
This line gets rendered in server side. It will not have any access to the browser's runtime context. As this gets executed before reaching the user.
var post = #{Post.find_by(id: post_value).to_json.html_safe};
Either use XHR (have another endpoint API purely for data objects like json) or query your Post object/s in controller, pass the object to the view and render the Post object inside the view. It is also a bad practice to have DB queries inside the view template files.
It's also weird to use javascript to render elements in the backend context. You generally use javascript with the context or assumption that it is to be executed in the user's side, separated with the backend context.

"Expression does not produce a value" in javascript, vb.net

In the Create View of the "Deal" model, I've defined a javascript function that creates a new object in a List Property when clicking a button.
I get the error "expression does not produce a value". I'm not expecting a value, I only need to create a new empty object in the list, so I don't understand this error.
javascript in my view, the line that adds the new Period to the list throws the error:
<script type="text/javascript">
function addRow() {
#Model.Periods.Add(New DealPeriod());
...
}
</script>
"Deal" Model:
Public MustInherit Class Deal
...
<Display(name:="Periodos")>
Public Property Periods As New List(Of DealPeriod)
There are two issues here - to cover the issue in the question "expression does not produce a value":
The #symbol here means "output the result of the following to the http response stream".
As List.Add() returns void, there is nothing to send to the response stream, so it gives you that error message.
Put another way, the # needs a value and List.Add() does not generate a value.
The second issue is that it appears you are mixing server-side execute with client-side execution (note I don't say server-side/client-side code, that's allowed in a similar way to how you have it). It appears you want to add a new "DealPeriod" when "addRow" is called - that's simply not how it works. The VB.Net code runs on the server and the javascript code runs on the client, in the browser. They are not linked together.
There are ways to link them such as an ajax call or signalr.
You are expecting #Model.Periods.Add(New DealPeriod()); to run when that javascript function is called, but that is not what is happening. The inline VB code is run server-side before sending HTML to the client.
With your webpage open, view source of the page and observe the code that gets rendered in that javascript function. You will not see that line of code.
What you want to do is make an ajax call to a controller that will perform the logic you want.

Accessing a local js variable in razor block

I am trying to write razor code inside javascript where I am trying to use a local variable inside the razor code. Here is the sample code:
<script type="text/javascript">
for (i = 0; i < data.result.length; i++) {
$("#member-table tbody").append("<tr>");
var id = data.result[i].MemberId;
var actions = $("<td>" + #Html.ActionLink("Detay", "Edit", new { id }) + "</td>)");
}
</script>
the problem is that id is not recognized by the razor code (i.e. it does not exist in the current context). How can I achieve that ? Is there any way ?
It's not possible to access a javascript variable in a razor block.
That's because razor is executed in the server, and javascript is executed in the browser.
However, by looking at your code it seems like you are using javascript to populate a table and that's bad, there are two patterns for solving this problem, one that solves everything in the server, and another one that solves everything in the browser.
Solving everything in the server:
If you decide that you want to solve everything in the server, your javascript should request the contents from the server and load them into a placeholder without changing them, something like:
$("#myButton").click(function(){
$("#myDinamicDiv").load("/Path/ToView");
});
and then you use razor's foreach loop to generate the table's html:
#foreach (var x in ViewBag.MyData)
{
<tr>
<td>Generate contents here, including links </td>
</tr>
}
Solving everything in the client:
As pointed out in another answer, if you are using the default routing, you can just create direct strings in the javascript code and add them to your page, keep in mind however, that when using this solution, as your page gets complex, your javascript will became less and less maintainable, having a for loop that iterates over data is a sign that maybe you can benefit from javascript UI frameworks like Angular.js and Knockout.js, in fact, what you are doing is the core of Knockout.js's third lesson in its tutorial (Single page applications)
If you're just using default routing, then simply just don't bother with the Razor #Html.ActionLink. Stick with an explicit tag:
var actions = $('<td>Detay</td>');
...obviously with whatever your current controller name is substituted for [your-controller-here].
(And I'm assuming your 'id' isn't necessarily URL-encoded, hence the 'escape'.)
You are mixing server side and client side here. You cannot create #Html.ActioLink using client side variables. Html.ActionLink is rendered on the server, it does not have any clue at all about your client side variables.
If you want to use a client side variable, like "id", render a plain html link (a) tag.
This worked for me once
if ('#ViewBag.DownloadLink' != '') {
window.location.href = '#ViewBag.DownloadLink';
}

Django custom template tags in javascript

I have a custom template tag that returns suppose name of a student and roll number if passed as an argument id of the student.
#register.inclusion_tag('snippet/student_name.html')
def st_name_tag(profile, disp_roll=True, disp_name=True):
#some calculations
return {'full_name':student.name,
'roll':student.roll_number,
}
The template(included) consists of some Html file which is written in a single line(to avoid unterminated string literal error from js).
I simply want to call the st_name_tag from inside the JS function.
My JS looks like:
{% load profile_tag %}
<script type = "text/javascript">
eventclick : function(st){
var div = ('<div></div>');
var st_id = st.id;
if (st.status == 'pass'){
div.append('<p>Student Name:{% st_name_tag '+st_id+' %}</p>');
}
}
So far I tried the above method along with removing the + and '' signs from st_id varaible. That hasnt helped me at all. Help Please!
You are trying to render a template based on the interaction by user. The first happens on the server (server-side as it is often referred to), and the latter happens on the user's browser.
The order that these happen is first to render the template on server, send and present in browser, then user interacts with js. Because of this fact, as I mentioned in the comment, it is not possible to affect the template rendered within javascript.
I would recommend you to use ajax in order to accomplish this. Whenever an iteraction occurs, you asynchronously make a request to the server to present you with new data.

Grails - rendering div with a javascript call within a remoteSubmit

I have a situation where I want to hit a button in the GSP (actionSubmit) and update a div when I finish the call (which includes a call to a javascript function). I want to ultimate end up in the controller rendering the searchResults parameter and the div with the results (which is currently working).
Problem is, I need to (presumably) wrap my actionSubmit in a remoteForm. But how do I:
1) Run the javascript method already existent in the onClick
2) Render the page in the controller.
If I try both wrapped in a controller, I finish the remoteForm action and the javascript action "hangs" and never finishes.
Any ideas?
List.gsp
<g:actionSubmit type="button" value="Ping All" onclick="getIds('contactList');"/>
function getIds(checkList)
{
var idList = new Array();
jQuery("input[name=" + checkList + "]:checked").each
(
function() {
idList.push(jQuery(this).val());
}
);
$.ajax({
url: "pingAll",
type:"GET",
data:{ids:JSON.stringify(idList)}
});
}
controller:
def pingAll() {
String ids = params.ids
if(ids == "[]") {
render(template:'searchResults', model:[searchResults:""])
return
}
def idArray = contactService.formatIDString(ids)
idArray.each {
def contactInstance = Contact.get(Integer.parseInt(it))
emailPingService.ping(contactInstance)
}
/**
* Added this on 3/13. Commented out line was initial code.
*/
def searchResults = contactSearchService.refactorSearchResults(contactSearchService.searchResults)
render(template:'searchResults', model:[searchResults:searchResults, total:searchResults.size()])
}
You have a couple options:
1) You can avoid using the Grails remote tags (formRemote, remoteField, etc.), and I really encourage you to explore and understand how they work. The Grails remote tags are generally not very flexible. The best way to learn how they work is to just write some sample tags using the examples from the Grails online docs and then look at the rendered page in a web browser. All the tags do generally speaking are output basic html with the attributes you define in your Grails tags. Open up your favorite HTML source view (i.e. Firebug) and see what Grails outputs for the rendered HTML.
The reason I say this is because, the code you've written so far somewhat accomplishes what I've stated above, without using any GSP tags.
g:actionSubmit submits the form you are working in using the controller action you define (which you haven't here, so it runs the action named in your value attribute). However, you also have an onClick on your actionSubmit that is running an AJAX call that also submits data to your pingAll action. Without seeing the rest of your code and what else is involved in your form, you are submitting your form twice!
You can simply just not write actionSubmit, and simply do an input of type button (not submit) with an onClick. Then in your javascript function that runs, define a jQuery success option for your AJAX call
$.ajax({
url: "pingAll",
type:"GET",
data:{ids:JSON.stringify(idList)},
success:function(data) {
$('#your-updatedDiv-id-here').html(data);
}
});
2) If you want to use the GSP tags, I think you are using the wrong one. Without knowing the full extent of your usage and form data involved, it looks like g:formRemote, g:submitToRemote, and g:remoteFunction could serve your purposes. All have attributes you can define to call javascript before the remote call, as well as defining a div to update and various event handlers.

Categories

Resources