(VB) Passing a textbox value with a Url.Action via javascript - javascript

In VB, I am working on an MVC project. I have a text box to enter some search criteria, and a button next to it that upon pressing will submit the value of the text box. Html Snippet:
<input type="text" id="mySearchField" />
<button onclick="location.href='#Url.Action("Search", "Movies", New RouteValueDictionary(New With {.searchCriteria = document.getElementById('mySearchField') }))'">Search</button>
My question revolves around the final part:
New RouteValueDictionary(New With {.searchCriteria = document.getElementById('mySearchField') }))'"
The code above does not work or compile, but this is my general idea of what I am attemping to do.
I want to pass the value of the text box along into the Movies/Search function, however I am at a loss as to how to format the line to mix the html, asp, and javascript all at once.
My VB Function for clarity:
Function Search(searchCriteria As String) As ActionResult
Return View()
End Function
Any advice is much appreciated!

This should be pretty close. This has jQuery as a prerequisite. To make this maintainable (you can do this, or not), I'd use NewtonSoft.Json to serialize the URL to Javascript properly, and url-encode the text box value.
<input type="text" id="mySearchField" />
<button id=myButton>Search</button>
<script>
var url = '#Html.Raw(Url.Action("Search", "Movies"))';
$("#myButton").click(function(){
location.href = url + '?searchCriteria=' + $("#mySearchField").val()
});
</script>

Related

How can I get an HTML tag’s value to send an HTML.Action()

I have these lines of code:
<span
class="close-modal"
onclick="#Html.Action("SaveNotes", "CallCenter", new { activityId = item.callIdKey, noteText = "test1" })">
×
</span>
Notes: <br />
<textarea name="paragraph_text" rows="5" style="width:90%">
#item.NoteText
</textarea>
I would like to replace test1 from the noteText route variable and instead change it to whatever the value in the <textarea> tag is.
Is there an elegant way of doing this without writing a giant block of jQuery code?
#Html.Action() renders a partial view as an HTML string during page processing (on the server side). It doesn't exist any more in the markup, once the page is sent to the browser. You can't do what you are trying to do this way. At the very least, I'm sure you don't want to render a partial view inside the onclick event of your <span> tag.
Why not instead use an HTML helper for the <textarea> tag? Then you can get whatever value the user typed into it on the server code. You'll want to make the form post itself back to the server on the close-modal element:
<span class="close-modal" onclick="$('form').submit()">×</span>
<form method="post" action="#Url.Action("SaveNotes", "CallCenter", new { activityId=item.callIdKey }">
Notes: <br />
#Html.TextArea("noteText", item.NoteText, new { rows="5", style="width:90%" })
</form>
This assumes you have jQuery already (a common assumption with ASP.NET). You may not need the <form> tags if you already have a form on your page.
A #gunr2171 notes in the comments, the only way to dynamically update a link once it's been rendered to the browser is via some form of client-side scripting, typically JavaScript. In your case, I'd recommend doing something like this:
<span
class="close-modal"
data-href-template="#Url.Action("SaveNotes", "CallCenter", new {activityId = item.callIdKey, noteText="{note}"})"
>
×
</span>
Note: As #HBlackorby notes in his answer, you shouldn't be using #Html.Action() here; I assume you meant #Url.Action().
This way, your JavaScript has a template (data-href-template) that it can work against with a clearly defined token ({note}) to replace, instead of needing to parse the URL in order to identify where the previously replaced text is. Otherwise, you potentially end up in a scenario where you type e.g. CallCenter into your <textarea /> and it's now an ambiguous reference that you can't just blindly replace. Or, worse, you type 'a' and it's really ambiguous.
If you are already using jQuery on your site, the actual replacement might be done using something along the lines of:
$(document).ready(function () {
$('span.close-modal').click(function() {
var noteInput = $('textarea[name="paragraph_text"]');
var encodedNote = encodeURI(noteInput.text());
var template = $(this).data("href-template");
var targetUrl = template.replace("{note}", encodedNote);
window.location.href = targetUrl;
});
});
You can also do this without jQuery, obviously—and should if you're not already depending on it. The point is to illustrate that this doesn't necessarily need to be a "giant block of jQuery code". In fact, this could be done in just a few lines—and probably should be. I deliberately broke it out into multiple steps and variables for the sake of readability.

How to access an URL from a function in HTML/Javascript?

So I started to learn HTML and JavaScript not long ago and I wonder how I could access an URL/download a file from a function I made with JavaScript in another file and imported it with
<script src="jscriptSheet.js"></script>
Maybe I am wording the search badly but I didn't found anything that helps me. The only thing I saw, was doing a form and sending it to a server, but that's not what I need (I think).
What I'm doing is creating 2 dates that need to be passed to the URL so it can access the file and download it:
<div class="dateWrapper">
<p id="date1">Date1:</p>
<input id="date1INPUT" type="date">
<p id="date2">Date2:</p>
<input id="date2INPUT" type="date">
<br><br>
<button id="datesubmit" type="submit" onclick="downloadF()">Download file.</button>
</div>
And the function made with JavaScript:
function downloadF{
href="100.100.100.100/something/something.php?date1="+ date1 from the input above +"&date2="+ date2 from the input above +"&something=10.php"
}
When I execute this, it downloads nothing, it's just a normal button with no action.
How can I do it?
You do not want type=submit if you want to do something else than submitting. INSTEAD use a button as below or attach to the submit handler of the form and use preventDefault if you do not want to submit
I use location= you can use window.open(url) too but that may be blocked
Also your function should be
function functionname() { ... }
Anyway here is an example
document.getElementById("datesubmit").addEventListener("click",function {
location="100.100.100.100/something/something.php"+
"?date1="+document.getElementById("date1INPUT").value+
"&date2="+document.getElementById("date2INPUT").value
})
<div class="dateWrapper">
<p id="date1">Date1:</p>
<input id="date1INPUT" type="date">
<p id="date2">Date2:</p>
<input id="date2INPUT" type="date">
<br><br>
<button id="datesubmit" type="button">Download file.</button>
</div>
If you set the header in the PHP you will see a download dialog
header("Content-type: application/octet-stream");
Welcome to stackoverflow!
As already mentioned in a comment, you don't want to have the type set to "submit" when the button should not really submit the inputs but call a custom javascript function. Instead you just want to have the type set to "button".
Moreover you should define your javascript function like this (watch out for the parentheses):
function downloadF(){
// Access your input fields here
}
For accessing DOM elements you might want to have a look here at w3schools
function downloadF{
href="100.100.100.100/something/something.php?date1="+ date1 from the input above +"&date2="+ date2 from the input above +"&something=10.php"
}
this is having invalid syntax. The JavaScript function should be defined like ( Very basically),
var f1 = function(){
}
function f2(){
}
And,
href="100.100.100.100/something/something.php?date1="+ date1 from the input above +"&date2="+ date2 from the input above +"&something=10.php"
Here you are inserting something like date1 & data2 But it's not exist in your function. You can't use undefined variables.
And if you skip all syntax errors and look at the command
href="100.100.100.100/something/something.php?date1="+ date1 from the input above +"&date2="+ date2 from the input above +"&something=10.php"
you are just setting a variable href and you didn't do any actions.
First learn basic javascript https://developer.mozilla.org/en-US/docs/Web/JavaScript
And the answer of your question is,
If the target file is directly downloadable, you can use window.open('the_target_url') inside function.
If not,
You should do something in PHP. Please refer this link Download file from PHP

Using JS to read from a JSON file when button is clicked

I'm trying to solve a problem where a user inputs values into a search box, presses the search button and with the onClick event the search terms are compared to values in a JSON file. Currently I don't know jQuery so if this can be avoided in the solution I would appreciate it! What I have so far is:
<div id="searchb">
<button onclick="userSearch()">Search</button>
</div>
This is a simple div for the search button which calls the userSearch function that deals with the JSON file:
<script>
<!--Function which compares inputted name to names in the .json file. -->
function userSearch(thearr) {
... <!-- All of the code that compares the values -->
console.log();
}
</script>
<script src="filepath on my machine">
</script> <!-- Source path to .json file for script -->
The issue that I'm having is that the function in the onClick event doesn't pass any parameters, because the parameter for userSearch is not defined until the script tag is reached. When I run this 'applet' I get an error saying that the parameter thearr is undefined.
The file path is correct because I used it for a similar problem which automatically generated results from the JSON file on page load, it's the button click that seems to be the problem. Any ideas on how this issue could be fixed would be greatly appreciated! Thanks.
EDIT: Search box HTML as requested
<div id="textboxes">
<textarea id="input1" placeholder="First Name" rows="1" cols="10">
</textarea>
<textarea id="input2" placeholder="Surname" rows="1" cols="10"></textarea>
</div>
From your question, it sounds like you need to get the values from the users input. For userSearch(thearr), i'm not sure what you expect thearr to be. You can get the value of the user input like this:
function userSearch() {
var firstName = document.getElementById("input1").value;
var surName = document.getElementById("input2").value;
console.log(firstName + " " + surName);
}
Note: if you are expecting to process multiple first/surnames, you should rethink the architecture. The logic to do so with the current set up would not be simple to write and more importantly unnecessary.

javascript split text into list of words and then dynamically added to div, form tag messing it up

I was testing this code out in an asp.net webform as I am looking to split a text into a list or words in javascript and have each added to its own div.
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_split
However in an asp.net webform, the sample code alone produces strange behavior, and the result appears and disappears. Simply adding the form tags to the online sample reproduces the behavior.
<form id="form1" runat="server">
</form>
Is there a workaround for this or alternative ideas to do this in javascript?
Thanks
The behavior you are experiencing is happening because the button is triggering a postback to the server. This essentially reloads the page which is why it appears as though the text is appearing then disappearing right away.
You can fix this by adding in a return false; after onclick="myfunction()" like this:
<form id="form1" runat="server">
<p>Click the button to display the array values after the split.</p>
<button onclick="myFunction();return false;">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "How are you doing today?";
var res = str.split(" ");
document.getElementById("demo").innerHTML = res;
}
</script>
</form>
However, I do not recommend using the onclick attribute to call a JavaScript function as there are better ways to do this. For the purpose of your example, I provided the simplest solution to the problem, but I want to make you aware that there are better ways to handle this.
As an extension to Howard Renollet's explanation for the form behavior:
A <button> element has different types. W3Schools mentions that "different browsers may use different default types for the element."
When in a form, the submit and reset types will actually do things to the form! In order to put a button into a form without it submitting the form, set the type to button:
<form>
<button type="button">Yay, I won't submit this form!</button>
</form>

Mixing razor syntax with Javascript in views

What's the proper way to go about it. I need it to work like in the example below.
<input type="button" value="Resume" onclick="window.location = '/Test?testid=#(ViewBag.TestID)'" />
I absolutely support Zabavsky's comment that you should use an ActionLink for this specific example in order to have semantically correct markup.
But since you asked:
Mixing razor syntax with Javascript in views
Never do that.
In your view you should have only markup:
<input type="button" value="Resume" id="myButton" data-url="#Url.Action("Test", new { testid = ViewBag.TestID })" />
and javascript (IN A SEPARATE FILE) where you could work with this markup and unobtrusively enhance it:
$(function() {
$('#myButton').click(function() {
window.location.href = $(this).data('url');
});
});
Of course if the user has javascript disabled your web application is completely busted. That's why you should always write semantically correct markup. In this case that would be to use an anchor because in HTML buttons are used to submit forms, anchors are used to redirect to some other location (which is exactly what you are trying to achieve in this specific case).
I would, as Zabavsky said, use an ActionLink for this:
Something like this:
#Html.ActionLink("Resume", "Test", new { testid = ViewBag.TestID })
There are quite a few overrides for actionlink, so you need to pick the one which fits your needs.
The one above output an a href with the text 'Resume' going to action 'Test' on the current controller, passing a routevalue of testid = ViewBag.TestID
You can do it like:
<html><head><script>function newDoc() { window.location.assign("http://www.abc.com") }</script></head><body><input type="button" value="Load new document" onclick="newDoc()"></body></html>
Hope it will help. Thanks.
Well, what you wrote is valid.
You may have VS underline your code in red cause it think you have a js error due to the '' string not ended... but if you run it, it works.
To avoid red underline, you could do :
#{string js = "window.location = '/Test?testid="+ViewBag.TestID+" '";}
<input type="button" value="Resume" onclick="#js" />

Categories