passing textbox value to controller on button click? - c#

I need to pass textbox data to controller action on a button click. Here is my code:
<input id="txt" type="text">
<button onclick="#Url.Action("MyAction", "Mycontroller", new {currencyCode=ViewBag .currencyCode,endDate=Model.StartDate, value entered in txt above})" >
I cant use form here. Can you please suggest me how I can access/ pass this value to action ?
Thanks for your help and guiding me.

The code below sends the text-box value to the controller's action.
<input id="txt" type="text">
<button id="button">Click Me</button>
#section Scripts {
<script type="text/javascript">
$("#button").click(function () {
var txtVal = $("#txt").val();
window.location = "#Url.Action("TheAction","TheController")" +
"/" + txtVal;
});
</script>
}

You can use something like
<div>
<input type='text' name='UnboundTextBoxName' />
</div>
MVC will automatically take the value of UnboundTextBoxName and insert that value into the parameter of the same name.

You should be using <form> tags and set the action to your controller and have set a place in your model to store the data.

This would help you get the value entered in the text box to be the part of the url and in turn hit the required action in your controller specified
<form id = "form1" runat="server">
<asp:TextBox id= "txtbox" runat="server"></asp:TextBox>
<input type="button" id = "searchbtn" value="Search" onclick="srch_Click()"/>
</form>
<script type ="text/javascript" >
function srch_Click() {
var host = window.location.host;
var txt = $("#txtbox").val();
var path = "/CONTROLLER/ACTION/" + txt;
window.location.pathname = path;
var url = host + path;
window.location(url);
}
</script>
any improvisation to the above code is welcomed

Related

C# - How to pass html input value to url.Action

I have an input and a button. input's value supposed to be passed to #url.Action like description in code below:
<input class="in-class" id="textbox" type="text" runat="server" />
<button class="btn-class" id="press" type="button" onclick="location.href='#Url.Action("Index", "Home", new {id = /*Value Of textbox*/ })'" >click here</button>
As I mentioned in code, /*Value Of textbox*/ should be input's current value.
Change the href value with jQuery or JavaScript like this:
<button class="btn-class" id="press" type="button" onclick="changeHref()" >click here</button>
function changeHref(){
var url = '#Url.Action("Index", "Home")';
var txtVal = $('#textbox').val();
window.location.href = url + '/?txtVal=' + txtVal;
}
I use this form
<input type="text" id="txtValue" />
<input type="button" value="Detail" onclick="location.href='#Url.Action("Action", "Home")?Value=' + $('#txtValue').val()" />
or you cant write this in jquery function.
I preferred using jQuery click handler since you have button ID and following standard event registration model to separate HTML & JS:
HTML
<input class="in-class" id="textbox" type="text" />
<button class="btn-class" id="press" type="button">click here</button>
JS
$('#press').click(function () {
var url = '#Url.Action("Index", "Home")';
var textValue = $('#textbox').val();
window.location.href = url + '?id=' + textValue;
});
PS: No need to use runat="server" attribute in MVC since Razor doesn't require it.

C#,HTML how can i populate html text box with values saved in session or values handled at server side?

I have some textbox values in aspx page,which i pass on to the next page using sessions,but now i want to populate these values in a html textbox .How can i do it?The values that i have are server side ,where as HTML text box value is client side(this is just my assumption,i can be totally wrong on this part).
The reason why i want to do this is i got code from the internet which gives location,map between two points,the directions between the source and destination,but it is using html textbox and i think it is using ajax (i have 0 knowledge of ajax) so if i replace html textbox with asp.net text box .I dont get the auto address completion feature .
the aspx page is ,i am not able to understand the java script here cause it is very complex for me:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var source, destination;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
var mumbai = new google.maps.LatLng(27.4667, 89.6417);
var mapOptions = {
zoom: 7,
center: mumbai
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvPanel'));
//*********DIRECTIONS AND ROUTE**********************//
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
var dvDistance = document.getElementById("dvDistance");
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration;
} else {
alert("Unable to find the distance via road.");
}
});
}
</script>
<input type="text" id="txtSource" style="width: 315px" />
<span class="auto-style4">Destination: </span>
<input type="text" id="txtDestination" style="width: 318px" />
<br />
<br />
<input type="button" value="Get Route" onclick="GetRoute()" style="margin-left: 437px" />
Can anyone please help me out with this .
You can embed the the values directly into the html textbox using embedded code, this is done in the .aspx file not the code behind (aspx.cs):
<input type="text"><%= Session[""].ToString() %></input>
more information on embedded code blocks:
https://msdn.microsoft.com/en-us/library/ms178135%28v=vs.140%29.aspx
Consider this as input text box
<input type="text" id="inputtextbox"/>
Using Javascript you can assign the data in session in to input text box
document.getelementbyid("inputtextbox").value = <%= Session[""].ToString() %>
You can actually have a HTML textbox like this:
<input type="text" id="text1" />
To access it from code-behind without any help from javascript, you can simple add runat="server" to the textbox and it can be called from code-behind.
So, it becomes something like this:
<input type="text" id="text1" runat="server" />
And you can do like this to add it to the textbox from code-behind:
text1.Text = Session[""].ToString();
Tip: Always check to see if session is null before applying the value .

How to retrieve values from TextArea in a Local Variable in ASP MVC

I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.
In a view, I have 2 DropDownList and TextArea and 2 buttons :
DropDownList Poste
DropDownList Fonction
Button Ajouter
Button Enregistrer
TextArea
The Values of the TextArea are added from the DropDownList 'Fonction' when I click on the button 'Ajouter'.
I want to retrieve those values in a local variable. And that when the user click on the button 'Enregistrer'(submit).
This is the code of the view :
<% using (Html.BeginForm("Store", "Fonction")) { %>
<h2>GĂ©rer les droits</h2>
<form id="form1" runat="server">
<fieldset><legend>Gestion</legend>
<div>
<%:Html.Label("Poste :")%><%: Html.DropDownListFor(model => model.SelectedPoste, Model.PostesItems)%>
</div>
<br />
<div>
<%:Html.Label("Fonction :")%><%: Html.DropDownListFor(model => model.SelectedFonction, Model.FoncItems, new { #id = "ff" })%>
</div>
<br />
<div><input type="button" value="Ajouter" id="aj" onclick="addtext()"/></div>
<br />
<div>
<textarea id="tt" cols="10" name="S1" rows="8" readonly="true"></textarea>
</div>
</fieldset>
<br />
<div><input type="submit" value="Enregistrer" id="sv" /></div>
</form>
<script language="javascript" type="text/javascript">
var storedValues = [];
function addtext() {
var ff = document.getElementById('ff');
var tt = document.getElementById('tt');
var selectedValue = ff.options[ff.selectedIndex].value + " ";
if (storedValues.indexOf(selectedValue) === -1) {
storedValues.push(selectedValue)
tt.value = storedValues.join('')
}
}
</script>
and this is the code of the methode store (for the submit) in the controller :
[HttpPost]
public ActionResult Store(FlowViewModel model)
{
if (ModelState.IsValid)
{
Fonction_Poste FP = new Fonction_Poste();
FP.ID_Poste = model.SelectedPoste;
FP.ID_Fonction = model.SelectedFonction;
FP.Droit = 1;
System.Web.UI.HtmlControls.HtmlTextArea htaDemo = (System.Web.UI.HtmlControls.HtmlTextArea)(form1.FindControl("tt"));
String Value = htaDemo.Value;
db.Fonction_Postes.Add(FP);
db.SaveChanges();
}
return RedirectToAction("Index");
}
So as you see, Itried to do retrive values using this statement but that's didn't give any result :
System.Web.UI.HtmlControls.HtmlTextArea htaDemo = (System.Web.UI.HtmlControls.HtmlTextArea)(form1.FindControl("tt"));
String Value = htaDemo.Value;
If you have any property in the FlowViewModel for the value of the text area to bind to, you can use it.
If you have any property with the name S1, the value of the text area will be automatically bound.
Because, in ASP.Net MVC, there are no server side controls that you can refer to. Everything is model bound automatically.
Else, you can either create a property or use the FormCollection to get the value and use it accordingly.
Please share your implementation related to this to guide better.

How to get a html tag innerHTML of client side code?

Using asp.net and c# on a sharepoint server I edit the innerhtml of a div tag that has runat="server", and I place lots of html code in it and an input box (this input box is the autocomplete jquery UI input box).
I can give the input box an id.
Now how can I access the text in the input box in c#?
searchbox.InnerHtml = #"
<script type='text/javascript'>
$(function() {
var availableTags = [
" + results + #"
];
$( '#tags' ).autocomplete({
source: availableTags
});
});
</script>
<div class='demo'>
<div class='ui-widget'>
<input id='tags'>
</div>
</div>";
You want an HTML parser. You can try out this library. Specifically, if you use Chrome.. right click the box itself and 'Inspect it'. Right click the inputbox, and hit 'Copy XPath'. This is the path, now just select the element with HTMLAgilityPack.
You cannot directly access to the value of the input box from the server side code. You either need to post it back or send the value of the input box by an Ajax request to the server.
Post back using form & submit
<form action="yourpage.aspz" method="POST">
<input type="text" name="inputbox" id="inputbox"/>
<input type="submit" name="submit" value="submit"/>
</form>
And for the Ajax code with JQuery:
<input type="text" name="inputbox" id="inputbox"/>
<input type="button" name="submit" value="submit" onclick="ajaxPost();"/>
<script type="text/javascript">
function ajaxPost(){
var inputBoxValue=$("#inputbox").val();
$.post("yourpage.aspx", { inputbox: inputBoxValue } );
}
</script>
Yourpage.aspx.cs
// ... some other code
var a = Request.Form("inputbox")
// ... some other code

Need to SelectAll or Clear all checkboxes

Please help I am trying to code for selectAll or clear all using Jquery. I have a checkboxlist and the value of id seems to be incorrect. Id in firebug shows the value "<%= checkboxId.ClientID %>"
Thanks
SA
Part of the code:
Select All |
Clear All
<asp:checkboxList id="checkboxId" runat="server" />
Script:
function selectClearAlltest(id, value) {
var chks = $("#" + id + ":input");
chks.attr("checked", value);
}
Your selector is wrong, it makes #checkboxId:input. You should add another space (you're looking for descendants), and better:
var chks = $("#" + id + " input:checkbox");
If Firebug is showing you <%= and %> then it means your page was not parsed/interpreted by the server properly.
These character sequences are usually meant to signify server-processed code, and not make their way into the actual markup. For example, are you trying to execute ASP code in an ".html" file? Or, ... are you trying to execute ASP code on a PHP-based server?
Another way to verify this is to just do a view source on the page, and see if your server-generated code is actually being generated!
Best of luck!!-Mike
adding a class name would make things simpler
e.g.
<asp:checkboxList id="checkboxId" runat="server" CssClass="whatever"/>
and the jQuery code:
function selectClearAlltest(value) {
$(".whatever").attr("checked", value);
}
or even better using jQuery.toggle as
$("#select_all_element_id").toggle(
function () {
$(".whatever").attr("checked", "checked");
},
function () {
$(".whatever").removeAttr("checked");
},
);
Example:
<html>
<head>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<a id="toggle-select" href="#">select/deselect all</a>
<hr/>
<input type="checkbox" class='foo'>Click</input>
<input type="checkbox" class='foo'>On</input>
<input type="checkbox" class='foo'>The</input>
<input type="checkbox" class='foo'>The</input>
<input type="checkbox" class='foo'>Link</input>
<input type="checkbox" class='foo'>Above</input>
<input type="checkbox" class='foo'>To</input>
<input type="checkbox" class='foo'>Change</input>
<input type="checkbox" class='foo'>My</input>
<input type="checkbox" class='foo'>Attributes</input>
<script>
$(document).ready(function(){
$("#toggle-select").toggle(
function () {
$(".foo").attr("checked", "checked");
},
function () {
$(".foo").removeAttr("checked");
}
);
});
</script>
</body>

Categories