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.
Related
I am trying to retrieve data from a controller. This is a new twist on my Json error. I added a function to the index.cshtml page and I try to add code to get the information from the controller. I added a basic code to write a string to the textbox (all local) and that worked. When I tried to call from the controller it doesn't matter what the code is I get this error:
(source: mousecreations.com)
I have tried the following with the same error. Probably some other combinations that I have found in my search.
$.getJSON(#Url.Action("GetIPAddress","getipaddress"),
$.get(......)
$.ajax(......)
The entire function
function processgetip(event)
{
// Within this function, make an AJAX call to get the IP Address
$.getJSON(#Url.Action("GetIPAddress","getipaddress"), function (ip) {
// When this call is done, your IP should be stored in 'ip', so
// You can use it how you would like
// Example: Setting a TextBox with ID "YourElement" to your returned IP Address
$("#facility").val(ip);
});
}
This error is different than any of the others so what in that process event would cause the other processes to be undefined?
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.
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
I am very new to Python programming, so please bear with me.
I have an HTML file with several div layers. This file is opened in a webkit.WebView object. Each div layer saves a value in a global variable (JavaScript) when clicked upon.
How can I read the value of that global JavaScript variable from my Python script?
I found some answers but they don't seem to fit my situation (but I can be wrong, of course):
Passing JavaScript variable to Python
Parse JavaScript variable with Python
[EDIT]
I'm using webkit.WebView because I have to show this in an existing glade (libglade) application.
try this out. It uses the addToJavaScriptWindowObject method to add a QObject into the QWebView. This will enable communication between your python script and the HMTL/Javascript in your webview. The example below will let you change the value of the javascript global variable message to whatever value you want through a JavaScript prompt, then whenever you click on the Python Print Message link it will execute your python code that will take the javascript value and just print it to the console.
import sys
from PyQt4 import QtCore, QtGui, QtWebKit
HTML = """
<html><body onload="broker.print_msg(message)">
<script>var message = 'print_msg message'</script>
Change Message<br/>
Python Print Message
</body></html>
"""
class Broker(QtCore.QObject):
#QtCore.pyqtSlot(str)
def print_msg(self, data):
print data
app = QtGui.QApplication(sys.argv)
view = QtWebKit.QWebView()
view.page().mainFrame().addToJavaScriptWindowObject('broker', Broker(view))
view.setHtml(HTML)
window = QtGui.QMainWindow()
window.setCentralWidget(view)
window.show()
sys.exit(app.exec_())
I know this is old question, but still answering it with the hope that it will be useful to someone.
You can use alert handler and read the value in python side. http://webkitgtk.org/reference/webkitgtk/stable/webkitgtk-webkitwebview.html#WebKitWebView-script-alert
Example on button click you can have action that says
alert("Button Clicked");
On python side you will get the alert notification and you can parse the string. If the object is not a simple object, you will have to convert it to string format that can be parsed on python side. I have seen few examples of alert handler. https://github.com/nhrdl/notesMD/blob/master/notesmd.py is one that I wrote and uses alert handlers to pass lot of data between javascript and python
I have an update panel with a timer control set up to automatically check for some data updates every minute or so.
If it sees that the data updates, it is set to call a local script with the serialized JSON data.
ScriptManager.RegisterStartupScript(UpdateField, GetType(HiddenField), ACTION_CheckHistoryVersion, "updateData(" & data & ");", True)
where "data" might look something like
{
"someProperty":"foo",
"someOtherProperty":"bar",
"someList":[
{"prop1":"value"},
{"prop2":"value"}, ...
],
"someOtherList":[{},...,{}]
}
"data" can get quite large, and sometimes only a few items change.
The problem I am having is this. Every time I send this back to the client, it gets added as a brand new script block and the existing blocks do not get removed or replaced.
output looks something like this:
<script type="text/javascript">
updateData({
"someProperty":"foo",
"someOtherProperty":"bar",
"someList":[
{"prop1":"value"},
{"prop2":"value"}, ...
],
"someOtherList":[{},...,{}]
});
</script>
<script type="text/javascript">
updateData({
"someProperty":"foo",
"someOtherProperty":"bar",
"someList":[
{"prop1":"changed"},
{"prop2":"val"}, ...
],
"someOtherList":[{},...,{}]
});
</script>
<script type="text/javascript">
updateData({
"someProperty":"foos",
"someOtherProperty":"ball",
"someList":[
{"prop1":"changed"},
{"prop2":"val"}, ...
]
});
</script>
with a new script block being created every time there is a change in the data.
Over time the amount of data accumulating on the browser could get potentially huge if we just keep adding this and I can't imagine how most people's browser would take it, but I don't think it could be good.
Does anyone know if there is a way to just replace the code that has been sent back to the browser rather than continuously adding it like this?
I came up with a hack that seems to work in my situation.
I am using jQuery to find the script tag that I am creating and remove it after it has been called.
Here is an example:
First I generate a guid:
Dim guidText as string = GUID.NewGuid().ToString()
I create a function like the following:
function RemoveThisScript(guid){
$("script").each(function(){
var _this = $(this);
if(_this.html().indexOf(guid)>-1)
_this.remove();
});
}
Then I add the following code to my output string:
... & " RemoveThisScript('" & guidText & "');"
This causes jQuery to look through all the scripts on the page for one that has the GUID (essentially the one calling the function) and removes it from the DOM.
I would recommend to use web service with some webmethod which you will call inside window.setInterval. In success handler of your webmethod (on client side) you can just take response and do whatever you want with it. And it will not be saved in your page (well, if you will do everything wrong). Benefit is that you will minimize request size(updatepanel will pass all your viewstate data, which could be large enough) and will limit server resources usage (update panel is causing full page live cycle, suppose slightly modified, but anyway - all those page_load, page_init, etc...) and with web service you will only what you need.
Here is an article where you can see how it could be created and used on client side. Looks like good enough.