Button Click Event not Passing input String to MVC Controller Method - javascript

I have the following view HTML
<input id="txt" type="text">
<button class="btn btn-primary" id="button">Upload</button>
and the script
<script type="text/javascript">
$("#button").click(function () {
var txtVal = $("#txt").val();
window.location = "#Url.Action("Upload", "Tools")" + "/" + txtVal;
});
</script>
My controller method is
[AllowAnonymous]
public async Task<ActionResult> Upload(string fileName)
{
string path = #"C:\GambitTests\blue-g-logo.jpg";
// Do stuff.
return RedirectToAction("Index", "Tools");
}
this method fires but I am not getting the text from the input box and fileName is null.
What am I doing wrong here how can I pass the text from the input control to this method?
Thanks for your time.

The default syntax for passing parameters in the query string is ?paramName=value, so in your case you'd need to change your JavaScript to:
window.location = "#Url.Action("Upload", "Tools")" + "?fileName=" + txtVal;
Alternatively, change the parameter name to id and it'll work as you expect (courtesy of the default RouteConfig).

Related

JSF custom component, pass data from JSF to Javascript and reverse

I want to build a custom component in JSF that could :
retrieve a value from its value attribute
display this value
be able to update this value through Javascript (will update bean attribute used in value component attribute)
<t:myComponent value="#{myBean.value}" />
will display
<div>
<input id="my_input" type="text" value="my_value" />
<button onclick="update_value(document.getElementById('my_input').value)">update</button>
</div>
<script>
function update_value(val) {
// ???
}
</script>
and when we click the button, it will change myBean.value by the current content of the input (that user can change obviously).
As I understand, it looks easy to display the value in the component with the ResponseWriter but I do not understand how to build Javascript to call the component to change the value of the component.
example
// myBean.value = "foo"
<t:myComponent value="#{myBean.value}" />
// displays
<div>
<input id="my_input" type="text" value="foo" />
<button ...>update</button>
</div>
// user change input content by "bar"
// user click the update button
// myBean.value = "bar" now
Pass Bean Values to Javascript
There are some ways to do this. I think the most obvious way of doing this is rendering a script tag and putting the information in this.
Single Value:
writer.write("var value = '" + yourValue + "';");
Map Values:
String s = "var values = {";
for (Entry<String, String> entry : map.entrySet()) {
s += entry.getKey() + ": '" + entry.getValue() + "',\n";
}
s = s.trim().substring(1, s.length() - 1); // removes last ','
s += "};";
writer.write(s);
List Values:
String s = "var values = [";
for (String value : list) {
s += "'" + value + "', ";
}
s = s.trim().substring(1, s.length() - 1); // removes last ','
s += "];";
writer.write(s);
I would recommend not to put everthing in this script because this would be very much code in the encode methods. Rather have the static javascript code in a .js file and just write the dynamic content in the script tag. See how to get variables from other scripts.
Another way does not need a script tag. This way would call a js method like this:
function init(values) {
// ...
}
In the Renderer just call the js method:
facesContext.getPartialViewContext().getEvalScripts().add("init(" + yourValue + ");");
Pass Javascript values to Server-Side
Just include an input like this:
// just a random unique id
String generatedId = context.getClientId(context) + ":utility";
// ...
writer.startElement("input", null);
writer.writeAttribute("id", generatedId, null);
writer.writeAttribute("name", generatedId, null);
writer.writeAttribute("type", "hidden", null);
writer.endElement("input");
Then pass the generatedId with the other values to javascript.
In Javascript:
function setValues(value) {
// hiddenInputId is the server-side generatedId
var input = document.getElementId(hiddenInputId);
input.value = value;
}
Then just send an ajax request and get the values in the decode method like this:
// same id as in the encode methods
String generatedId = context.getClientId(context) + ":utility";
Map<String, String> map = facesContext.getExternalContext().getRequestParameterMap();
String value = map.get(generatedId);
// ...

Calling a Javascript in my razor page from a controller in MVC4

In my controller I have this function:
Function AppError() As ActionResult
Dim myScript As Object = "popup(" + Properties.postError + ")"
Return RedirectToAction("main", myScript)
End Function
With this function I want to call my razor page where I have a Javascript named popup whith a parameter Properties.postError.
My script is:
<script type="text/javascript">
var errMsg;
function popup(msg) {
errMsg = msg;
window.alert(errMsg);
window.window.focus();
if (window.confirm)
errmsg = '';
msg = '';
}
</script>
What I need is to popup the error message.
I follow the programm thru my debugger and I saw that it goes to my page.
But no error message window raise up.
I have already search in the web for this option without any success.
Is someone to assist me on this issue?
ADDITION - 16/2/19 12:50
what I have done so far is the following:
Function CBError() As ActionResult
Dim myScript As Object = "popup(" + Properties.postError + ")"
ViewData.Add(New KeyValuePair(Of String, Object)("ScriptName", myScript))
Return View("main", myScript)
End Function
As we can see I've change the function by addiding the ViewData
I Add a value pair arguments 1) the name 2) the value
The action of addition it works just fine and the dictionery receive it.
I my script (which is in my reazor page) I put the following:
<script type="text/javascript">
var vd = #ViewData.Item(0);
function popup(msg) {
var errMsg;
errMsg = msg;
window.alert(errMsg);
window.window.focus();
if (window.confirm)
errmsg = '';
msg = '';
//{ window.location.href = "/" }
}
</script>
When I stop (with the bebugger) in the instruction var vd = #ViewData.Item(0); I see that the ViewData is complitely empty. No values no nothing.
I also add this window.onload = #Html.Raw(ViewBag.MyScript);
And in debugger threw me an error
"Uncaught SyntaxError: Unexpected token ;"
Is there somone to instruct me why that happen?
ADDITION - 16/2/19 20:00
New version of function and Script
Function CBError() As ActionResult
Dim myScript As Object = Properties.postError
ViewData.Add(New KeyValuePair(Of String, Object)("Message", myScript))
Return View("main")
End Function<br/>
<script type="text/javascript">
$(document).ready(function (){
alert("#ViewData.Values(0)");
});
</script>
With this version I put the message value to the ViewData
But when the program comes to the point of script then all the ViwData is empty.
No Values no Keys no nothing.
It seems somewhere in the middle it lose all the data
FINAL UPDATE 17/2/19 11:13
The problem has been solved ... but not by the way we are wearing.
It was solved in an extremely simple way.
What we were asking for was to get the error message on the page we are in. From any point of the code.
So I followed the method of rendering the message to property and I read this message from the page with the following Javascript.
The function is:
Function CodePage_Error() As ActionResult
Return View("main")
End Function
End the Javascript is:
<script type="text/javascript">
$(document).ready(function () {
if ("#Properties.InnerError" !== "") {
var msg = "#Properties.InnerError";
window.alert(msg);
} else {
return false;
}
});
The Javascript is placed in the mainLayout.vbhtml file
Generally speaking, it turned out that the transfer method from the controller to the page is not possible in the MVC4 environment
You could pass the error message to the page via Viewbag, and then put the pop up script inside the document ready javascript function to check the message and display the error if required.
Controller:
public IActionResult Index()
{
ViewBag.Message = "this is your message";
return View();
}
View:
<script type="text/javascript">
$(document).ready(function (){
alert("#ViewBag.Message");
});
I think passing JS code through RedirectToAction route value parameter is not a good idea because some special characters will be encoded. You should use either ViewBag or viewmodel properties and pass the script to view in unencoded state.
Here is an example setup:
1) Use ViewBag or a viewmodel property to contain the script you want to execute in the view.
Public Function AppError() As ActionResult
' define Properties.postError here
Dim myScript As String = "popup(" + Properties.postError + ")"
ViewBag.MyScript = myScript
Return View()
End Function
2) Use an event handler e.g. window.onload assigned with #Html.Raw() from ViewBag or viewmodel property to pass unencoded function call inside <script> tag. The event handling must be placed outside function block.
<script type="text/javascript">
var errMsg;
function popup(msg) {
errMsg = msg;
window.alert(errMsg);
window.window.focus();
if (window.confirm)
errmsg = '';
msg = '';
}
// the popup will be called here
window.onload = #Html.Raw(ViewBag.MyScript)
</script>
Note that window.onload will pop up the message after the view is loaded, if you want to pop up the message in another event use any desired event handler instead (also check list of available JS DOM events).

Sending java script variable value as part of PostBackUrl query string

I need to send a parameter value into a query string of a PostBackUrl method
within asp button.
The value I need is already being captured within a java script function shown below.
How do I send the value in hiddId as part of URL ? The below method isn't working. Can someone please help ?
<script language="javascript" type = "text/javascript">
function btn_Selected() {
var hiddId = null;
$('#<%=GridView1.ClientID %>').find('input[type=radio]:checked').each(function () {
hiddId = $(this).closest('tr').find('input[type = "hidden"]').val();
});
}
<asp:Button ID="Btn_Update" runat="server" Text="Update" PostBackUrl="Screen_Edit.aspx?CustID='<%=hiddId%>'"
Instead of a post-back, just redirect using JavaScript.
function btn_Selected() {
var hiddId = null;
$('#<%=GridView1.ClientID %>').find('input[type=radio]:checked').each(function () {
hiddId = $(this).closest('tr').find('input[type = "hidden"]').val();
});
window.location.href = "Screen_Edit.aspx?CustID='" + hiddId + "'"
}
If you look at the HTML source of the page, the button will have an javascript onclick event that looks something like this javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$mainContentPane$Btn_Update", "", false, "", "Screen_Edit.aspx?CustID=", false, false))
All we have to do is find a way to insert your variable after ?CustID=.
You can replace the onclick value of the button with the .attr() function of jQuery and do a search and replace to insert your variable.
<script type="text/javascript">
$(document).ready(function () {
var hiddId = $(this).closest('tr').find('input[type = "hidden"]').val();
$("#<%=Btn_Update.ClientID %>").attr("onclick", $("#<%=Btn_Update.ClientID %>").attr("onclick").replace("?CustID=", "?CustID=" + hiddId));
});
</script>

Passing a field of a domain object into javascript function in grails

I want to pass a field of a domain object to a javascript function in my view.gsp (grails) , but I am getting a syntax error.
Here is my gsp and javascript - please let me know if you see the syntax error. Thanks!
/*HTML*/
<td>${fieldValue(bean: studentInstance, field: "active")}</td>
/*JS*/
<script type="text/javascript">
var id = 0;
function setID(userId){
console.log("userId: " + userId);
id = userId;
}
</script>
The issue is you have function in your onclick. You don't need it there. Remove it so your onclick looks like this:
onclick="setID( ${studentInstance.id})"

Passing querystring from one page to another through javascript

I have two different pages. I want to send querystring from one to another. below is my sample code that i have tried
window.location.search = 'id='+hidposid.value;
window.location.href="editviewposition.aspx";
in another page i retrieve the value
cookie1 = HttpContext.Current.Request.QueryString("id") ' returns ""
<script type="text/javascript">
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
window.location.href = url;
});
});
</script>
<input type="button" id="btnQueryString" value="Send" />
Hope this will help u..
I think I'd rather do something like
window.location.href= 'editviewposition.aspx?id=' + hidposid.value;
Or is there a reason this is not possible?
Here you are passing query string not cookies
Get it like
window.location.search = '?id='+hidposid.value;
window.location.href="editviewposition.aspx";
and then in code behind
HttpContext.Current.Request.QueryString("id")

Categories