Im working in a MVC .NET application. I assign a value to an element ID like this:
document.getElementById("latbox").value = event.latLng.lat();
and I retrieve it to show it like this:
<p>Latitud: <input size="20" type="text" id="latbox" name="lat" ></p>
The thing is, how can I find this value in my controller? Thanks.
In your view, you can use a <input type='hidden' name='lat'/> that you assign the value you need. Note that it must match the name of your controller parameter
#using (Html.BeginForm("Action", "Controller", FormMethod.Post))
{
<p>Latitud: <input size="20" type="text" id="latbox" name="lat"></p>
<input type="hidden" name="lat" id="latbox-hidden" />
<input type="submit" value="submit" />
}
<script type="text/javascript">
var lat = document.getElementById("latbox");
lat.value = "foo";
document.getElementById("latbox-hidden").value = lat.value;
alert(document.getElementById("latbox-hidden").value);
</script>
And your controller:
[HttpPost]
public ActionResult Action(string id, string lat) //same name to bind
{
//do your thing
}
HTML fields are posted using the name attribute, which in your case is "lat". On the controller you could have a parameter like this:
string lat
It would get the value of the HTML input element.
You can also use ajax call to send data to action
<head runat="server">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/AjaxTest/FirstAjax'; // give path of your action
var param = document.getElementById("latbox");
$.ajax({
type: "POST",
url: serviceURL,
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
Related
I'm looking for help about this subject.
I've got in my view 2 textbox.
I would like to get a value (generated in my controller) applied to textbox2 when there is an change on the textbox1.
For example I enter an username in textbox1 and textbox2 is the email address getting from controller (we can imagine that the controller check in a database or an active directory).
My code below seems not working:
In my View file I added an script section :
#section scripts{
<script type="text/javascript" language="javascript">
function ShowPersonalPanel(myChkboxPersonalLine) {
if (myChkboxPersonalLine.checked == false) {
$("#1-w").hide("fast");
}
else {
$("#1-w").show("fast");
}
}
</script>
<script language="javascript">
$("#1-w").hide("fast");
$('#myOtherGID').change(function () {
var myOtherGID = this.value;
$.getJSON("/PhoneController/GetEmailByGID",
{
strGID: myOtherGID
},
function (data) {
$('myOtherEmail').val(data);
});
});
</script>
}
And the code in the view with textbox:
<label for="myOtherGIDlbl">GID:</label>
<label class="text" id="myOtherGIDlbl">
#Html.TextBoxFor(model => model.myOtherGID)
</label>
<label for="myOtherEmaillbl">Email:</label>
<label class="text" id="myOtherEmaillbl">
#Html.TextBoxFor(model => model.myOtherEmail)
</label>
On my controller (named PhoneController) I added an action:
public JsonResult GetEmailByGID(string strGID)
{
string strEmailAddress = "this is my email";
return Json(strEmailAddress, JsonRequestBehavior.AllowGet);
}
As I work with an _layout.cshtml and an viewFile.cshtml, I added in the layout (in the head section) the line below:
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
What did I miss?
Regards
I've found my issue.
I've changed my javascript to make an $.ajax command:
script type="text/javascript">
$('#myOtherGID').change(function () {
var selection = $('#myOtherGID').val();
if (selection.length > 0) {
var url = "/Phone/GetEmailByGID";
$.ajax({
type: "POST",
url: '#Url.Action("GetEmailByGID", "Phone")',
dataType: "json",
success: function(data, status) {
alert(data);
},
error: function() {
alert('error');
}
});
}
});
</script>
In the controller :
[HttpPost]
public ActionResult GetEmailByGID(string strGID)
{
string strEmailAddress = strEmailByGID(strGID);
return Json(strEmailAddress);
}
After testing, I can retrive data from my controler to my View without reloading all page.
I am following some online ajax tutorials, the example is about calling a webapi using GET method, here is the script section on the page
<script type="text/javascript">
$(document).ready(function () {
var ulEmployees = $('#ulEmployees');
$('#btn').click(function () {
$.ajax({
type: 'GET',
url: "http://localhost:35468/api/employee",
dataType: 'json',
async: true,
success: function (data) {
ulEmployees.empty();
$.each(data, function (index, value) {
var fullName = value.FirstName + ' ' + value.LastName;
ulEmployees.append('<li>' + fullName + '</li>');
});
}
});
});
$('#btnClear').click(function () {
ulEmployees.empty();
});
});
</script>
It should render the emoloyee first and last name within a list item in the .
<div>
<input id="btn" type="button" value="Get All Employees" />
<input id="btnClear" type="button" value="Clear" />
<ul id="ulEmployees">
</ul>
</div>
the each function iterates the on the object but it displays undefined in the html
does anyone know a solution to this ?
Solved
the problem was because the field names FirstName and LastName was incorrect,
correct field names are firstName and lastName thats why the object was not populating them in a correct manner.
The code below sends the id of item to more.php to load more content. It works fine. Now to add some more features I need to send one more id to more.php through the same code.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.display').append(html);
}
});
});
});
</script>
Suppose second id is var catid = '<?php echo $cat ?>'; how to send this catid through the same ajax code. data : {id : id, catid : catid} is something I should do but can't get how to deal in current situation when my data carries data:'id='+ID,.
your should look like. specify your data as an object:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.show_more', function () {
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type: 'POST',
url: 'more.php',
data: { id:ID, userid: userid },
success: function (html) {
$('#show_more_main' + ID).remove();
$('.display').append(html);
}
});
});
});
To retrieve multiple input's I suggest combining them in a Form:
first embed your inputs in an form with a submit button, you should also not use the same name twice because it won't work now, create unique names
<form action="GET" id="myForm">
<input id="string" type="text" name="string" />
<input id="string2" type="text" name="string" />
<input type="submit" value="Go" />
</form>
and write code to submit the ajax way
$('#myForm').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
var $form = $(this);
$.ajax({
type: "GET",
url: "retrieve.php",
data: $form.serialize(), //make it JSON
success: function() {
console.log("it worked");
}
});
});
I have a textbox which is passed to the api....the text entered is stored...
<input type="text" id="name" placeholder="Type something">
The below code works in developer mode of chrome with breakpoints but doesnt work without it...
$("#submit").click(function() {
var name = $('#name').val() ;
var url = "https://www.mariyano.com/app-server/test/?action=add_list&name="+name;
$.ajax({
url: url,
dataType: "jsonp",
});
Actually no idea what's wrong but here is a working source code: http://jsfiddle.net/HLmsr/
JavaScript
$("#submit").click(function() {
var name = $('#name').val() ;
var url = "https://www.mariyano.com/app-server/test/?action=add_list&name="+name;
$.ajax({
url: url,
dataType: "jsonp",
error: function (e) {
console.log(e);
},
success: function (data) {
console.log(data);
}
});
});
HTML
<input type="text" value="" id="name" />
<input type="button" id="submit" value="Submit" />
Try to modify your code like this:
$("#submit").click(function(evt) {
evt.preventDefault();
var name = $('#name').val() ;
...
If you don't call preventDefault and "submit" is a submit-input type, it could happen that the code is not executed because instead the browser navigates to another page.
See jquery reference for more details: jquery
I have an ASP.NET MVC3 app and when the user clicks on my anchor tag, I want to send 3 pieces of data to an action:
<a onclick='editDescription(<#= DocID,FileName,Description #>)'></a>
This is the javascript to call my action:
function editDescription(docId,fileName,description) {
var url = "#Url.Content("~/OrderDetail/_EditDescription/")" + docId+'/'+
fileName + '/' + description;
//do the rest}
My action:
public ActionResult _EditDescription(string id,string filename, string descritpion)
The pieces im concerned about are FileName and Description because these can be loooooong and i dont want a url to appear like so:
http://localhost/OrderDetail/_EditDescription/123/some long filename.pdf/this is a long description for the name
How can i send across my data to my action without having to send it like a query string? Thanks
You can use the jQuery $.ajax method:
<div id="what-I-want-updated">
<input id="whatever-the-id-is" type="text" value="#Model.ID" />
<br />
<input id="whatever-the-filename" type="text" value="#Model.Filename" />
<br />
<input id="whatever-the-description" type="text" value="#Model.Description" />
<br />
<button id="whatIsClicked">Update!</button>
</div> <!-- /#what-I-want-updated -->
<script>
// You're probably clicking something to initiate update
var $whatIsClicked = $('#whatIsClicked');
// .live persists on the page even after other ajax calls
// So when the thing is clicked
$whatIsClicked.live('click', function() {
// Grab the information needed to update
var theId = $('#whatever-the-id-is').val(); //Or it could be .text()
var theFilename = $('#whatever-the-filename').val();
var theDescript = $('#whatever-the-description').val();
// Let's edit the description!
$.ajax({
type: "POST",
url: "OrderDetail/_EditDescription", // the method we are calling
contentType: "application/json; charset=utf-8",
data: {id: theId, filename: theFilename, description: theDescript},
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
// Or if you are returning something
alert('I returned... ' + result.WhateverIsReturning);
},
error: function (result) {
alert('Oh no :(');
}
});
});
</script>
Even though it will still work, make sure you change your Controller method to:
[HttpPost]
public ActionResult _EditDescription(string id, string filename, string descritpion)
You can do a full post of the form if you like either through ajax $.post or by having an action with [HttpPost] attribute.
Declare your action as a POST
[HttpPost]
public ActionResult _EditDescription(string docId, string filename, string description)
Create an invisible HTML form:
<form action="#Url.Content("~/OrderDetail/_EditDescription/")" method="post" name="editDescriptionForm">
<input type="hidden" name="docId" />
<input type="hidden" name="fileName" />
<input type="hidden" name="description" />
</form>
Fill out the form and submit it with JS:
function editDescription(docId, fileName, description) {
document.editDescriptionForm.docId = docId;
...
document.editDescriptionForm.submit();
}