How to dynamically grab data and post it - javascript

Hello everyone I'm using ASP.NET C# MVC architecture to do this.
Right now I have a View "Index.cshtml" which has a table.
<table id="myTableData">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
</tr>
</thead>
<tbody>
<tr>
<td>val1</td>
<td>val2</td>
<td>val3</td>
<td>500</td>
<td>val5</td>
</tr>
<tr>
<td>val1</td>
<td>val2</td>
<td>val3</td>
<td>1500</td>
<td>val5</td>
</tr>
</tbody>
</table>
<script>
init();
function init(){
addRowHandlers('myTableData');
}
function addRowHandlers(tableId) {
if(document.getElementById(tableId)!=null){
var table = document.getElementById(tableId);
var rows = table.getElementsByTagName('tr');
var AB = '';
var BC = '';
var CD = '';
var DE = '';
for ( var i = 1; i < rows.length; i++) {
rows[i].i = i;
rows[i].onclick = function() {
AB = table.rows[this.i].cells[0].innerHTML;
BC = table.rows[this.i].cells[1].innerHTML;
CD = table.rows[this.i].cells[2].innerHTML;
DE = table.rows[this.i].cells[3].innerHTML;\
};
}
}
}
</script>
Currently I can grab all the information within a row with this script and I'll probably use this ajax to do the post
<script>
function seleccionar() {
$.ajax({
url: '#comercial.Models.Base.DirectorioRaiz()MovimientosCliente/SeleccionarOperacion',
type: 'post',
dataType: 'json',
contentType: 'application/json',
data: { operacion: operacion, metodo: metodo, monto: monto, fecha: fecha },
success: function (response) {
$('#divModalDeFacturas').html(response);
},
error: function (error) {
console.log(error);
}
});
}
</script>
Basically what I need is to grab all the data of a row I select with a buttom and use ajax to post it to another view, can anyone explain this to me?
How can I put both scripts to work together?
I know how to handle FormCollection form data that I post using inputs, most of the times I use hidden inputs inside the td's of the table but I require to do this dynamically and it gets a little difficult that way because I can't put static variables to pull the data, at least the way I tried it, it did not work.
Right now I think the best way would be to put this data in my controller, I've read another stack answer that says that these inputs are grabbed by the controller using paramters inside the ActionResult like this
[HttpPost]
public ActionResult MyView(int val1, int val2, intval3, etc...)
{
return View();
}
I dont know I feel lost browsing the sea of data available on the internet D:
This is answer I said that shows how to retrieve this information by the controller
Link to answer

First of all your action must be decorated with the HttpPostAttribute if you are looking to use POST in your example. The view you must return has to be specified on your return statement:
[HttpPost]
public ActionResult MyView(int val1, int val2, intval3, etc...)
{
return View("The view you want to return");
}
Also looking at your question and javascript code it's not clear what you're aiming for, are you looking to populate an area in your index view with some dynamic content, or are you looking to redirect to another view?
Then your javascript code is quite wrong as well. First of all you are specifying a a json object on your 'data' parameter, but then you're setting the content type to 'application/x-www-form-urlencoded' instead of 'application/json'. Also, If you're trying to post a json, then your 'datatype' should be 'json' not 'text'.
Then your url, appears to be wrong. To avoid confusion and error always use the Url.Action method where you can specify the required action an controller.
To be honest, if I was you, I would revisit the MVC docs, since it appears that you are missing a lot of knowledge on MVC, as it provides a lot of examples and walkthroughs which are really helpful. (https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/).
I would also suggest a recap on the Http protocol, which you can google and there's plenty of sources out there.

Related

Customizing DataTables with WEB API OData service for filtering EF - column search not working

I am using DataTables on the client side and ASP.NET WEB API OData queryable service on the server side. The issue with sorting and filtering DataTable columns on the server side is that DataTables are generating that awful super long request with all columns info, even when they are not used for sorting or filtering. I've decided to write custom AJAX call from client to server to create neat odata query, that can be applied easily to EF context. Unfortunately column searching fields have stopped rendering as a inputs. What can be the issue?
JavaScript and HTML code:
$(document).ready(function() {
var options = new Object();
options.searching = true;
options.searchable = true;
options.aoColumns = [{
"sName": "USER_NAME",
"searchable": true
}];
options.bProcessing = true;
options.bServerSide = true;
options.sAjaxSource = "http://localhost/api/list";
options.fnServerData = function(sSource, aoData, fnCallback) {
var filter = "$top=5"; //just as example
$.getJSON(sSource, filter, function(json) {
fnCallback(json);
});
}
$('#myTable').dataTable(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<table id="myTable" class="table">
<thead>
<tr>
<th>
First Name
</th>
...
</tr>
</thead>
<tfoot>
<tr>
<th>
First Name
</th>
...
</tr>
</tfoot>
</table>
The service works fine, and looks like this (I've made this code as easy to understand as possible).
C# code:
public HttpResponseMessage List(ODataQueryOptions<User> options)
{
var result = oDataQueryOptions.ApplyTo(_context.Users) as IEnumerable<User>;
JQueryJsonResponse jsonUserResult = new JQueryJsonResponse
{
Draw = xxx,
iTotalRecords = xxx,
iTotalDisplayRecords = xxx,
aaData = result.ToList()
};
return Request.CreateResponse(HttpStatusCode.OK, jsonUserResult);
}
I would expect something like this:
But I get this:
CAUSE
You have server-side processing mode enabled with options.bServerSide = true;. In server-side processing mode filtering, paging and sorting calculations are all performed by a server.
SOLUTION
You need to handle parameters sent by the client on the server and perform filtering, paging and sorting. See full list of parameters sent in server-side processing mode.
Alternative solution is to disable server-side processing mode with options.bServerSide = false; and let DataTables perform filtering, paging and sorting on the client side.
OK, the question is not well formed, sorry. What I meant, that I want to apply column search to my datatables. During the copy-paste phase from other table I just missed some lines of code.
I've added something like this, and now it's working!
// Setup 'Search'
var filterSelector = '#myTable' + ' tfoot th';
$(filterSelector).each(function() {
var searchbox = $(this);
searchbox.html('<input type="text" class="form-control" placeholder="Search" />');
});
//Apply DataTables
var table = $('#myTable').DataTable(options);
$('.dataTables_filter input').attr("placeholder", "Search");
// Apply generic search
table.columns().every(function() {
var that = this;
var thatFooter = $('input', this.footer());
thatFooter.on('keyup change', function() {
that.search(this.value).draw();
});
});

Asp Net MVC 5 refresh a table in a partial view

So i ran into a little problem and i am having a hard time understanding what I should do to get the result I want/need.
So my application is supposed to show the route a certain object made in the last 2 hours. When the user loads the app they see several points scattered through out the map and when they click on one of those objects the route it made in the last 2 hours is shown, and a table I have is supposed to be updated with those coordinates. Now I make the call to fill the partial view when I get all the locations the object went to in the controller method.
this is how I start all of this (when the user clicks a point the following is executed)
(I am using openlayers 3 but it is irrelevant to this question)
$.ajax({
type: "GET",
url: '/Controller/GetRoutes',
dataType: "json",
success: function (result) {
alert('Added');
var layerLines = new ol.layer.Vector({
source: new ol.source.Vector({
features: [
new ol.Feature({
geometry: new ol.geom.LineString(routes, 'XY'),
name: 'Line'
})
]
})
});
map.addLayer(layerLines);
},
error: function (xhr, ajaxOptions, thrownError) {
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
So as you can see from this code the method GetRoutes() is going to be responsible for getting the information on where the object has been to.
This is the controller (I omitted most of the code thats responsible for drawing the actual routes since its quite a bit chunky)
[HttpGet]
public JsonResult GetRoutes()
{
var lastpoints = get an arraylist with all the points I want
var name = get the name of the object
RouteInformation(lastPoints,name);
return Json(lastPoints, JsonRequestBehavior.AllowGet);
}
I know I should probably change something here but i do not know what.
The method that gives me the last points is not mine, but I am required to use it so I have no other choice but to accept the arrayList it returns to me.
this is the RouteInformation method
public ActionResult RouteInformation(ArrayList routeList, string name )
{
List<ObjPoint> routes = routeList.OfType<ObjPoint>().ToList();
List<ObjRoute> objRoutes = new List<ObjRoute>();
objRoutes.Add(new ObjRoute()
{
name = name,
ObjPoints = routes
});
return PartialView("RouteDetailsView", objRoutes);
}
My issue is updating/refreshing that table, I have it in a partial view but I have no idea on what I have to do in order update that table with the information I want to display (i can get that information I just can´t seem to show it).
ObjPoint is composed of latitude,longitude, date, time.
This is the ObjRoute model
public class ObjRoute
{
public string name { get; set; }
public List<ObjPoint> ObjPoints { get; set; }
}
And now the Views ...
this is how the "main view" calls the partial view
<div>
#Html.Partial("routeDetailsView")
</div>
And this is my partial view
#model webVesselTracker.Models.ObjRoute
#{
ViewBag.Title = "RouteDetailsView";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
<table id="routeTable" class="table">
<tr>
<th>
Name
</th>
<th>
Latitude
</th>
<th>
Longitude
</th>
<th></th>
</tr>
#if (Model != null) {
foreach (var item in Model.ObjPoints)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Latitude)
</td>
<td>
#Html.DisplayFor(modelItem => item.Longitude)
</td>
</tr>
}
}
else
{
<tr>
<td>
No object has been selected, please select one
</td>
</tr>
}
</table>
</div>
Now I know I could probably do this by adding some sort of json request in the js file and from there on build the table, but I would like to know how to do this with Razor and where I have gone wrong in the code/logic.
Am I supposed to add some ajax elsewhere?
So to summarize this:
-User sees points.
-User clicks point to see the route it made.
-App draws the route and then sends the route information to a method table so it can be added to the table
the user can see that information
Thank you for your time and if I missed something please point it out so I can fix or explain it better.
I finally gave up and looked into knockout.js, it managed to solve all the issues I was having
knockout.js

Jquery Loop through table with multiple class

I am trying to loop through the table after the AJAX call is finished using the Jquery. But I am not able to loop through that.
My HTML Looks like this :
<table id="planyourwork" class="data-view plan-internal displayTable">
<thead>All Headers</thead>
<tbody>
<tr class="odd">
<td class="invisible"></td>
....
....
<td class="cell-status"></td>
</tr>
<tr class="odd">
<td class="invisible"></td>
....
....
<td class="cell-status"></td>
</tr>
<tr class="odd">
<td class="invisible"></td>
....
....
<td class="cell-status"></td>
</tr>
<tbody>
In JS file after calling the AJAX
$('.data-view > tbody > tr > td.cell-status').each(function() {
trying to add tool tip
}
When I debug, I see that Loop is not getting through. Debugger is stopping at data-view, but not looping through.
Please help me to resolve this problem
Below is the whole On Click event
filterBtn.click(function() {
loadData();
$('#planyourworktd.cell-status').each(function() {
var typeCell = $(this);
var tooltip = typeCell.parent().find('td.fullNotes').html();
alert("tooltip");
typeCell.attr('title', tooltip);
typeCell.tooltip({track: true,show: 100});
});
return false;
});
// Load the request and planner data
function loadData() {
$.ajax({
type: 'post',
url: url,
data: data,
cache: false,
success: function(html) {
initResults();
enableButtons();
},
error: function(jqXHR, textStatus, errorThrown) {
filterBtn.removeClass('invisible');
},
async: true
});
}
And DOM structure is quite complicated, when I run this in Fiddle it works but not on Page. I am not sure why? Thank you every one for helping me to resolve this.
Please Note : Syntax check may be typo error as I am removing production code, sorry for that.
There are a few mistakes in your html a javascript but I can't be sure whether it was when you typed it up here.
Anyways
'' is not closed, you have another '' instead of ''
You javascript is not closed properly, here is how it should look
$('.data-view > tbody > tr > td.cell-status ').each(function() {
console.log(this);
});
Notice the extra ');' at the end.
Now when I make these changes the output is fine.
I solved the problem. Its quite "sad", I missed few bits here. I am using struts 2 and AJAX call. and when an AJAX call is done, my event is called but by the time it is called data is not loaded. Reason is when an AJAX call is made, data is populated as "tile" which runs on its own. Rest of the elements are populated and data is loaded in parallel. Changing the location of the page solved the problem. Thank you for all your help.

Reloading using Angular

Hello friends from SO!
I'm new into angular, and I'm trying to keep a table always updated with the information comming from a PHP webservice.
I'm demanding the information the first time using the following:
HTML
<div class="block" ng-controller="demandar_informacion" ng-init="visualizacion_masiva()">
<h1 class="block_header">Welcome admin</h1>
<p class="block_info"></p>
<table>
<thead>
<tr>
<th ng-repeat="header in headers ">{{header}}</th>
</tr>
</thead>
<tr ng-repeat="disponible in disponibles">
<td ng-repeat="(variable, valor) in disponible">{{valor}}</td>
</tr>
</table>
</div>
Then I'm using the following code to get the information:
Js Angular:
function demandar_informacion($scope, $http) {
//pedido de visualización masiva
$scope.visualizacion_masiva = function() {
var address = "http://127.0.0.1/usa/_code/index_records.php"
+ "?ac=view_all"
var pedido = $http({
method: 'GET',
url: address
})
.success(function(data, status) {
$scope.errors = data.error;
$scope.headers = data.headers;
$scope.disponibles = data.disponibles;
$scope.eliminados = data.eliminados;
$scope.info = data.info;
});
};
}
Main Q:
Is there any way I could re-send the HTTP packet and update the information every, let's say, 3 or 5 seconds? as It's rapidly changing.
Auxiliary:
At the same time, this fragment of code, seems to be altering the order of the values I have on the array, or it might be previously altered somewhere in the Angular code. I've checked the PHP and the Json string seems to be in right conditions, but when it comes to printing the values, it completely looses it's native order (shows the elements in an improper / unknown order)... anyone has a clue?
<tr ng-repeat="disponible in disponibles">
<td ng-repeat="(variable, valor) in disponible">{{valor}}</td>
</tr>
Thanks in advance!
Chris C. Russo
Update
$scope.update = function() {
$timeout(function() {
$http.get('lol').success(function() {
$scope.update();
});
}, 5000);
};
Old
Simplest way to do this:
$interval(function() {
demandar_informacion();
}, 5000);
buuuuutttt as MichaL pointed out in the comments what will happen is that 5 seconds will get eaten up as it becomes 5, 4, 3, 2, 1, DDOSing yourself due to the time it takes to complete the request.
Other ways:
Use firebase to wait and call the load function.
Long poll your php script.
You can use the $timeout service to call the server every few seconds. Or use websockets to push the changes from the server to your Angular app (with Ratchet, perhaps (http://socketo.me/))

Durandal. Pass additional data to other view

I've got a view that needs to be populated conditionally.
Scenario:
A manager will select a users name on screen B, then will be navigated to the same form the user filled in EG. screen A, except that the said manager will have the option to approve or deny the request of the user.
I've seen that in my VM on screen A I can do the following.
var vm = {
activate: function (data) {
console.log(data);
var id = data.id || -1;
if (id !== -1) {
router.isNavigating(true);
http.json('/api/user/'+ id )
.done(function (response) {
ko.viewmodel.updateFromModel(vm.userInfo, response);
router.isNavigating(false);
});
}
}
};
And then B (view & view model)
view
<table>
<thead>
<tr>
<td>User</td>
<td>Date Requested</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<tr>
<td>Mike</td>
<td>19 Jun 2013
</td>
<td>
<input type="button" value="Go" data-bind="click: function() { buttons.goTo(6) }" />
</td>
</tr>
</tbody>
</table>
viewmodel
define(['durandal/plugins/router'], function (router) {
var buttons = {
goTo: function (id) {
console.log('goTo clicked');
//this does work in conjunction with my code on B
router.navigateTo('#/userinfo?id=' + id);
}
};
var vm = {
buttons: buttons
};
return vm;
});
My issue is that I'm not sure what the best way/or how to for that matter to get Durandal to navigate to page A from B... Is what I'm doing right? As it feels a little bit "hacky"
The navigation, at least to me, is designed to mimic standard MVC web navigation. In this case, since you already know that you want to go to 6, why not use an anchor like so
<a href="#/userinfo?id=6"/>
A better way would be to register your route with an id splat like so your route would become
routes.map({route: 'userinfo/:id, ...
<a href="#/userinfo/6" />
This way you can access the splat on the activate method..there are several examples out there but I don't have links to them. Basically the activate method of your userinfo viewmodel will accept a parameter and from there you can load an entity or whatever you like. Hope this helps.
Brad

Categories

Resources