How to send javascript var in Html beginform in MVC3 - javascript

I am trying to send a JS variable using html beginform to controller action. Eg:
#using (Html.BeginForm("Index", "Contrl1", new { SPName = myJSVarcomeshere }, FormMethod.Post))
{
<button id="plot" type="submit" class="btn" > Plot </button>
}
Currently the problem is the JS var is not in scope. Can I use a hidden field to achieve this

Yes you are right. The #using statement which writes our your form is executed on the server - the Javascript variable is only present on the client. Therefore you will have to use a hidden field inside the form and populate that field with the value of your javascript variable. You need to do that once the document has loaded or somewhere below the hidden field.
Example:
#using (Html.BeginForm("Index", "Contrl1", FormMethod.Post))
{
<input type="hidden" name="SPName" id="SPName" />
<button id="plot" type="submit" class="btn" > Plot </button>
}
Then, use JS to populate the hidden field:
JQuery version:
<script>
$(function(){
$('#SPName').val(myJSVarcomeshere);
});
</script>
Plain JS version:
<script>
window.onload = function() {
document.getElementById('SPName').value = myJSVarcomeshere;
};
</script>

Related

Send button value by post request via jquery

My code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form>
<button id="test" value="123" name="test" >ok</button>
</form>
<script>
$(document).ready(function () {
$("#test").click(function() {
var combinedData = $("#test").serialize();
$.post(
"element_submit.php",
combinedData
).done(function(data) {
//alert("Successfully submitted!");
$("#result").html(data);
}).fail(function () {
//alert("Error submitting forms!");
})
});
});
</script>
<div id="result" ></div>
The element_submit.php file
<?php
//just to test it should output in the #result div
echo $_POST['test'];
?>
What I am trying to do is submit the with the value="attribute" so the data is serialized and send the post request, it's not like a submit when user insert a value and submit,What I need is to get the value attribute and submit to the php, this code is only for To simplify and illustrate what I am trying to do, because in this page I have the following buttons with ids #follow #unfollow so I need a way to get the button value to make the user follow and unfollow.
you need to serialize the form - not the elements within it .You can also have the triggering button outside the form which will prevent hte form from submitting on the button click.
<form id="testForm">
<input type="hidden" name="testInput" value="123"/>
</form>
<button name="test" id="testButton">submit</button>
...
<script>
$(document).ready(function () {
$("#testButton").click(function() {
var combinedData = $("#testForm").serialize();...
$(document).ready(function () {
$("#testButton").click(function() {
var combinedData = $("#testForm").serialize();
console.log(combinedData);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="testForm">
<input type="hidden" value="123" name="testinput"/>
</form>
<button id="testButton">Click</button>
Straight JS might help you out. Include a function that sends the id and get the value of that id. Then just send a regular post of the value without serialize... easier.
<script>
function fetchButtonValue(theId){
var p = document.getElementById(theId).value;
alert (p);
}
</script>
<button id="myFormBtn" value ="woo"
onclick="fetchButtonValue(this.id)">My Button</button>
this works...
You could also put a class on the button let's say class="followBTN" then on a click you could just snag the value by $(this).val() I'd use this method if I had more than one button per page.

ASP.NET MVC and Javascript - Submit button submitting form, onclick #URL.Action not firing

I have two submits, one to submit the form on page 1, the other to submit form on page 1 and redirect to form 2 on page 2.
<input type="submit" value="Submit and Add Expense" onclick="window.location.href='#Url.Action("Create", "Expense")';"/>
The issue is, when this secondary submit button is clicked it just submits the form just like the first submit button. It appears that the redirect #url.action is not firing. Thoughts?
The following code should do the trick.
<input type="submit" id="btnOne" value="One"/>
<input type="button" id="btnTwo" value="One"/>
<script>
var sample = sample || {};
sample.url = '#Url.Action("Create", "Expense")';
</script>
//you can move it to a separate file
<script>
$(function(){
$("#btnTwo").click(function(){
var form = $("form");
form.submit();
setTimeout(function() {
window.location.href = sample.url;
},100);
});
});
</script>
I wound up going the easy route of assigning value property to the button, and then checking the button value in the controller.
// View
<input type="submit" value="Submit" />
<button name="button" value="SubmitAndExpense">Submit and Add Expense</button>
// Controller
[HttpPost]
public ActionResult Create(string button)
{
if (button != "SubmitAndExpense") {...}
}

Javascript update razor variable using onclick element

Is it possible to update a razor variable using onclick on a element?
MVC VIEW:
#{
string iconNumber = "1";
}
<button type="submit" onclick="#iconNumber = '2'; alert('#iconNumber');"></button>
Console error:
Uncaught ReferenceError: Invalid left-hand side in assignment
Thanks
I am not able to understand from your comments for what purpose you trying to update the razor variable, but if you really wants to update your razor variable from 1 to 2 (from your question), then i would suggest to try like below
#{
int iconNumber = 1;
}
then,
<button type="submit" onclick="#(iconNumber++); alert('#iconNumber');"></button>
Hope it helps...But also note that iconNumber will increment on each click of button. So, I can help you if you show some more code
When reading this question the day after, one would think I was under the influence of drugs.
I came up with a better solution that only uses javascript variables:
VIEW:
<script>var iconNumber = 0;</script>
#using (Ajax.BeginForm("", "",
new AjaxOptions
{
OnBegin = "$('#iconElement' + iconNumber).attr('class', 'fa fa-spinner fa-spin');",
HttpMethod = "POST"
}))
{
Html input here
<button type="submit" class="btn btn-danger" id="IconElement1" onclick="iconNumber = 1;">
<button type="submit" class="btn btn-danger" id="IconElement2" onclick="iconNumber = 2;">
<button type="submit" class="btn btn-danger" id="IconElement3" onclick="iconNumber = 3;">
}
I can now disable the form after submit to prevent multiple requests. Because I don't start the spinner directly in onclick I don't have to disable the buttons, (spinner wont start).

how to invoke a jsp method onclick/on form submit

I have a jsp page with this code:
<script type="text/javascript">
function getWithdrawAmmount()
{
var withdraw=document.forms["WithdrawDeposit"]["AmountToWithdraw"].value;
document.getElementById('hidden').type = withdraw;
}
</script>
<form method="POST" name="WithdrawDeposit" onsubmit="getWithdrawAmmount()">
<table>
<tr><td><input type="text" size=5 name="AmountToWithdraw"></td>
<td><input type="button" value="Withdraw"></td></tr>
</table>
</form>
<input type="hidden" name="hidden" value="">
<% String AmountWithdraw = request.getParameter("hidden"); %>
<%!
public void Withdraw(){
int Amount = Integer.parseInt("AmountWithdraw");
Deposit deposit = new Deposit();
deposit.WithdrawMoney(AmountWithdraw);
} %>
I need to activate the Withdraw() method on form submit and get the text input.
the javascript hold the value inserted in 'hidden' and i can access it later.
but i can't call to : <% Withdraw(); %> from inside javascript.
how can i call Withdraw() after button click?
10x
First off your line of code has issues
document.getElementById('hidden').type = withdraw;
It is looking for an element with an id of hidden. Not a name, an id. So add an id to the element you are referencing.
Second you are setting a type. Don't you want to set the value?
So the HTML would look like
<input type="hidden" name="hidden" id="hidden" value="" />
and the JavaScript would be
document.getElementById('hidden').value = withdraw;
Now if you want to call a function on the server, you either need to post back the form or make an Ajax call.

How to only trigger a JavaScript function without the controller handling the request in NET MVC 3 Razor

I am struggling with something that I'm not even sure if possible.
I have a typical form page in an .NET MVC 3 Razor project. Within this page is a Google map with a search mechanism. The search is wrapped with a form that calls a JavaScript function to update the map if a location is found.
When I try to use it, the view's controller handles the request and the controller's model state is not valid (as the user hasn't finished with the rest of the form yet). The result is a representation of the page which resets the map (totally the opposite of what I'm after).
Here's a simplified version of the view:
#model OnlineEventReporting.ViewModels.ReportShortViewData
#{
Layout = "~/Views/Shared/_LayoutGoogleMap_with_all_js_code.cshtml";
}
<script type="text/javascript">
function showAddress(address) { [processing code] }
</script>
#using (Html.BeginForm("Index", "ShortReport", FormMethod.Post, new { name = "shortForm", id = "shortForm", data_ajax = "false" }))
{
#Html.ValidationSummary(true)
Info for the controller to handle:
#Html.TextBoxFor(model => model.AddressDetail.Street1, new { #maxlength = "50" })
<!-- I want this to 'fire' the JavaScript 'showAddress' function and for the controller to ignore it -->
<form style="text-align:center" action="#" onsubmit="showAddress(this.address.value); return false">
<input type="text" size="20" id="address" name="address" value="North Street, Guildford" />
<input type="submit" value="Search!" />
</form>
<div id="map" style="width: 100%; height: 400px; margin-left:20px;"></div>
More info for the controller to handle:
#Html.TextBoxFor(model => model.AddressDetail.Street2, new { #maxlength = "50" })
}
I realise I have a form within a form here but I'm not how else I could approach this as I need the map and search feature right in the middle of my main form.
Any help would be greatly appreciated.
Many thanks,
Chris.
Your code would produce invalid HTML - nested forms are not valid HTML.
The problem is that the input type="submit" probably causes the topmost form to submit instead of what you expect.
Why not have a normal button and attach the function to the click event?
What you are looking for is an AJAX request. Your controller will still handle the request. However, it will do it asynchronously, without a complete postback.
First of all, get rid of the nested form tag, you don't need it. Instead, try this:
Info for the controller to handle:
#Html.TextBoxFor(model => model.AddressDetail.Street1, new { #maxlength = "50" })
<!-- I want this to 'fire' the JavaScript 'showAddress' function and for the controller to ignore it -->
<input type="text" size="20" id="address" name="address" value="North Street, Guildford" />
<input type="submit" value="Search!" onclick="showAddress(this.address.value); return false;" />
<div id="map" style="width: 100%; height: 400px; margin-left:20px;"></div>

Categories