Asp Net MVC 5 refresh a table in a partial view - javascript

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

Related

How to dynamically grab data and post it

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.

How to dynamically show a button based on conditions where the value being used to determine what button to show isn't known until it's clicked?

If someone has a better title feel free to edit. I inherited a project from a developer who is leaving the company and I'm scratching my head trying to find a solution to a problem the existing code provides.
Code from the view:
<div>
<table class="table">
<tr>
<th class="border-bottom border-top-0">Action</th>
</tr>
#foreach (Step actionItem in Model.Steps)
{
#if (actionItem.HasRun == false)
{
<tr class="border-top-0">
<td>
#if (actionItem.ReturnsInfo == true)
{
<input type="button" value="Run Check" onclick="loadProcessingFeedbackPartial('#actionItem.StepID', '#Model.Client.DatabaseConnectionString' )" />
}
else
{
<input type="submit" value="Run Check" name="btnRunStoredProcedure" asp-action="CallStepStoredProcedure" asp-route-StepID="#actionItem.StepID" asp-route-StepCompleted="#actionItem.HasRun" />
}
</td>
</tr>
break;
}
}
</table>
</div>
Javascript being called from the button click:
<script type="text/javascript">
function loadProcessingFeedbackPartial(x, y) {
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
var stepId = x;
var databaseConnectionString = y;
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString },
function () {
$("#confirmButton").removeAttr("style");
});
}
</script>
Controller action:
public IActionResult ViewProcessingFeedBackPartial(int StepId, string DatabaseConnectionString)
{
FeedbackDetails feedbackDetails = new FeedbackDetails();
feedbackDetails.Data = _clientProcessingService.GetProcessingFeedbackDetails(StepId, DatabaseConnectionString);
return PartialView("_ViewFeedback", feedbackDetails);
}
The button in the view has an Onclick event that goes to the Javascript function, which loads a partial view with the data from the controller calling a service method. Here's where the problem is. If no rows are returned, I want to bypass the partial being drawn entirely.
So I changed the controller action around a bit to include a condition where if the feedbackDetails.Data has 0 rows to just call a different method from the service, process as normal, but return the View instead of a partial.
public IActionResult ViewProcessingFeedBackPartial(int StepId, string DatabaseConnectionString, int ClientId)
{
FeedbackDetails feedbackDetails = new FeedbackDetails();
feedbackDetails.Data = _clientProcessingService.GetProcessingFeedbackDetails(StepId, DatabaseConnectionString);
if(feedbackDetails.Data.Rows.Count == 0)
{
_clientProcessingService.RunProcessStepConfirmation(DatabaseConnectionString, StepId, ClientId, "No information returned, automatically proceeding to next step.");
return RedirectToAction("Processing", new { Id = ClientId });
}
return PartialView("_ViewFeedback", feedbackDetails);
}
This "worked", except since in the view it's being called in a Javascript function that loads a partial regardless, the view is returned inside that partial instead of the view being returned.
But I'm unsure how to fix this because without first clicking the button and attempting to populate that collection with data, I don't know if it's empty (and skip the partial) or it has rows (and draw the partial).
I attempted creating an intermediary controller action that returns a boolean and attempted to use the result of that inside the javascript function to either draw the partial or skip it based on the bool, but I'm not really the greatest at Javascript so I wasn't able to get it to work.
I'm unsure if the way to solve this involves creating logic that displays multiple buttons that route to different controller actions or javascript functions or just handling it all via Javascript somehow.
What would be a good way to go about solving this?
#Mkalafut, your jQuery function is loading the controller result directly into "#processingFeedbackPartialDiv" regardless of the result received. Better to pull this initially into a variable, then add some simple logic to decide what to do next. Potentially the controller can help by returning a null result that is easy to identify.
e.g.
$.get("url", { stepId, databaseConnectionString }, function (data) {
var result = data;
// Some example conditional logic - adjust as required
if (result != null){
$("#processingFeedbackPartialDiv").html(result);
$("#confirmButton").removeAttr("style");
}
});
Remember, jQuery load & get are both just shorthand functions for ajax, so if needs be you can customise the code further to get the flexibility you need.
https://api.jquery.com/jQuery.get/
https://api.jquery.com/load/

ASP MVC - many request at one Ajax.BeginForm click

I have question about requests - their count.
Im using Ajax.BeginForm and onSuccess option.
But when I click that form my JS handler for OnSuccess option fires up many times.
I looked up for my request and its looks like this:
Image with number of request
So my question is: why if I click on AjaxForm it makes many request?
Thanks
View with Ajax action link:
#foreach (var item in Model)
{
if (item.Accepted == false)
{
<text>
<tr>
<td>
#Html.DisplayFor(modelItem => item.Accepted)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsOrganizer)
</td>
<td>
#Html.DisplayFor(modelItem => item.PlayerRating)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Ajax.ActionLink("Akceptuj", // <-- Text to display
"AcceptPlayer", // <-- Action Method Name
new { id = item.PlayerId },
new AjaxOptions
{
HttpMethod = "POST",
})
</td>
</tr>
</text>
}
}
Controller action:
[Authorize]
public ActionResult AcceptPlayer(long id)
{
using (var Players = new DbMigrationExample2Entities())
{
Player playerToAccept = Players.Player.Find(id);
if (playerToAccept == null)
{
return HttpNotFound();
}
playerToAccept.Accepted = true;
Players.SaveChanges(); return View();
}
If you have included jquery.unobtrusive-ajax.min.js twice once in the layout once in the partial. So your browser executes the js inside twice which will subscribe twice on the form click event that is why doing two POST instead of one.
So you need to remove the jquery.unobtrusive-ajax.min.js from the partial.
Note: If your are using a partial with a layout you don't need to duplicate the js included in the partial because it's already done by the layout. There are some good articles about layouts and partials.
Second think if problem persist then the solution here :
First ajax request is sent multiple times
If nigher this all solution is not working in your case then definitely you need to change your Ajax.ActionLink into Html.ActionLink Like :
#Html.ActionLink(article.Title, new { controller = "Akceptuj", action = "AcceptPlayer", id = item.PlayerId }, new AjaxOptions { HttpMethod = "POST" })
Cheers !!

asp.net - Manipulate Page Content

I was wondering if anyone could explain how to manipulate content for various sections of a page depending on if a button is clicked. I think what I am looking for is similar to an include in php. I wasnt sure if asp.net had a way to do the same (partial view?) or if bootstrap/jquery is the way to go. I've included a .png to illustrate what I am trying to do.
I would like section b's content to change based on what button is selected in section A. While not necessarily relevant to this question.. I then would like various user inputs in section B to manipulate existing content in section C.
In your controller, have an action that returns a PartialView:
public PartialViewResult MyPartial(string someText)
{
var model = new MyPartialModel {SomeStuff = someText};
return PartialView(model);
}
Create the model and partial view as you would any other:
public class MyPartialModel
{
public string SomeStuff { get; set; }
}
Partial View:
#model ExampleApp.Models.MyPartialModel
#Html.TextBoxFor(m => m.SomeStuff)
Then on your page you can load in your partial via ajax with jQuery:
<div>
<button type="button" id="load-partial">Load The Partial!</button>
</div>
<div id="section-b"></div>
#section Scripts{
<script>
$(document).ready(function () {
$('#load-partial').click(function () {
$.get('MyPartial', { sometext: "Hello!" }).done(function (data) {
$('#section-b').html(data);
});
});
});
</script>
}
Edit to answer comment:
If you don't want to instantiate a new model in the controller each time, you can pass the model (more or less) directly from the view.
In you controller, have a very simple action that accepts a model as a parameter and returns the partial view. Note the HttpPost attribute.
[HttpPost]
public PartialViewResult MyPartial(MyPartialModel model)
{
return PartialView(model);
}
The model's got more than one property this time:
public class MyPartialModel
{
public string Name { get; set; }
public int Age { get; set; }
}
The partial's pretty much the same, except it now displays the new properties of the model.
#model MVCPlayGround.Models.MyPartialModel
#Html.TextBoxFor(m => m.Name)
#Html.TextBoxFor(m => m.Age)
The jquery on the main page/view is very also similar, but uses POST instead of GET.
// these could be anything, from control on the page, or whatever
var name = "James";
var age = 30;
$(document).ready(function () {
$('#load-partial').click(function () {
// note that Name and the Age are the names of the properties in our model
$.post('MyPartial', { Name: name, Age: age }).done(function (data) {
$('#section-b').html(data);
});
});
});
This works because when data transmitted via POST, it's treated as form data, and when the controller's deciding which action to use it'll look at the parameters for the actions, and compare them to the form data available. The MyPartialModel contains properties that match the form data, so it chooses that action. There are other subtle rules, but that's basically it. Behind the scenes it'll still be instantiating a model in the controller, it's just in the framework, not in the code you've written.
Another edit
Having just re-read your comment I don't think I've answered it fully.
If you want to save the changes you've made in a partial view to the main view, have some hidden fields in the main view to hold this data.
<input type="hidden" id="name-holder" />
<input type="hidden" id="age-holder" />
And then when you want to store a value to them, just set the values with jquery:
$('#some-save-button-maybe').click(function(){
$('#name-holder').val($('id-of-name-on-partial').val());
$('#age-holder').val($('id-of-age-on-partial').val());
});
When you click on a the button to show a partial, send the appropriate data to the controller to render in the partial:
$('#load-partial').click(function () {
$.post('MyPartial', { Name: $('#name-holder').val(), Age: $('#age-holder').val() }).done(function (data) {
$('#section-b').html(data);
});
});
Hopefully that's what you need...
Yes there are partial views in MVC, and they are usually belong in the Views/Shared folder of your project and are prefixed with a _ (i.e. _MyPartial.cshtml.
As #AdamHeeg pointed out in the comments, there are many tutorials on the web about this kind of setup and many different ways to achieve what you are after.
Here is roughly how I might tackle it...
HTML
<nav>
#Html.ActionLink("Button 1", "GetSectionB")
</nav>
<section id="sectionB">
<!-- Content here -->
</section>
JavaScript
$('nav a').on('click', function (e) {
e.preventDefault();
$.get(this.href, function (html) {
$('#sectionB').html(html);
});
});
Controller
public PartialViewResult GetSectionB()
{
var vm = new MyViewModel();
//do stuff
return PartialView("_SectionB", vm);
}

Partial view with ajax and jQuery UI.Dialog

I am using a standard MVC4 EF5 setup and have a standard view which loads data from the db onto a table.
At the start of the table I have a column for each record with an Add button. The functionality I want is to click the button, popup a model dialog box with a form and add something to the item in the grid that was clicked (a 1 to many).
Lets say I have a list of vans available shown in the list. And when I click the add button beside the particular van where I want to add a passenger, I want a popup to show that allows me to type the details of the passenger so they can be assigned to that van.
I think I am over complicating this. But my brain is fried. I tried partial views with ajax. I tried jQuery UI.Dialog. Im just lost. I am trying to figure out how to find the id of the record I clicked (given the buttons are all generated by a for each loop in the view as normal and numbering them 1 to X does not tell me the id of the record I clicked). So even if I get the popup showing, I wont know which van to assign the passenger to.
If your woundering where the passenger list is coming from, its another table. And effectively any passenger can be assigned to any van. Its hypothetical.
Im actually working on a document generator and so there is a many to many relationship between document parts and documents (a given document part, can appear or belong to many documents, and a document can contain many document parts). I know its messy, this is why I did not want to use the real example.
I'm thinking its maybe an easy enough problem to solve but I have been at it since Friday and the brain left home!
Edit: Adding Code:
Here is the main view: The main problem I am having with this is the way the grid is constructed. I think its partially razor, partially html, partially html helper, and partially javascript. I don't know which part is which, but I just need to get a popup to show for each button in the table, and to have an id I can assign values to. I cant figure out how to do it here.
Html.Grid(dbaccess().Where(c => something = something
).Select(o => new
{
Name = o.Name,
Comment = o.Comment,
Status = o.Status,
}
, "grdConfiguration", 0, htmlRowClass: (p) => (row++ % 2 != 0) ? "" : "oddRow"
, columns: new[]{
//THIS IS THE PROBLEM LINE BELOW .... It shows a button in the table, but...
//how do I make it unique. Is it even necessary to do so.
// How do I get the ID of the record at this location when this button is pressed.
//This is the code as originally posted: For context
new Helpers.GridColumn(value: (a) => "<input type=\"button\" class=\"btn\" id=\"BtnHello\" value=\"Add\" />"),
//for some reason when I try the following alternative as suggest by the answers so far - it doesn't work.
new Helpers.GridColumn(value: (a) => "<input type=\"button\" class=\"btn\" data-ThisId=\"#model.SomeId\" value=\"Add\" />"),
//THIS IS THE PROBLEM LINE ABOVE....
there is more columns but this button calls the jQuery...
On this view I also have some Div tags in which to load the partial... I can actually get this to popup. But that's about all I can do. And only when I click the first button in the table.
<div id='SomePopUp' style='display: none;'>
//#using (Html.BeginForm())
//{
// <div>
// <span class="display-label">Quantity: </span>
// <span class="display-field"><input type="text" id="txtQuantity" /></span>
// </div>
// <div>
// <span class="display-label">Comments: </span>
// <span class="display-field"><textarea rows="7"></textarea></span>
// </div>
//}
</div>
I also have a script section on this view with the code for the popup:
<script type="text/javascript">
$("#BtnHello").click(function ()
{
$("#SomePopUp").dialog(
{
resizable: false,
height: 400,
width: 400,
modal: true,
title:"add to {Some ID}:", //I want the id to show here so I know I have the record I want.
buttons:
{
Submit : function ()
{
$(this).dialog('Some Text');
},
Cancel: function ()
{
$(this).dialog('close');
}
}
});
});
</script>
I have a controller:
[HttpGet]
public ActionResult AddExtra(int id)
{
//Fairly sure I should be doing something with this id, but how do I get it from the button.
return PartialView();
}
And for the partial view I have
#model CM.ViewModels.AddExtraPackagesViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Add Something</h3>
</div>
<div>
//I was using ajax here...
#*#using (Ajax.BeginForm("DoSomething", "Something", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "list-of-something"
}))
{
<div class="modal-body">
#Html.TextBoxFor(x => x.Quantity);
#Html.TextAreaFor(x => x.Comment);
</div>
<div class="modal-footer">
<button class="btn btn-success" id="submit">Save</button>
Close
</div>
}
</div>
I made a little view model too but...
public class AddExtraViewModel
{
public int Id { get; set; }
public string Quantity { get; set; }
public string Comment { get; set; }
}
I apologise if this is all over the place but I did not write the original code. There were about 7 other programmers here before me and I'm just struggling to get through it.
Any help would be appreciated.
I think you would want something like this (using jQuery and jQuery UI):
Controller:
public ActionResult SomeAction(int id) {
return View(new YourModel { Id = id });
}
Partial View:
#model YourProject.Models.YourModel
// Partial view content e.g. the form etc.
Your view:
/<!-- html etc. -->
<table>
<tr>
<td>Add</td>
</tr>
</table>
<script>
$(function(){
$(".add-button").click(function(){
var options = {
autoOpen: false
}
var dialog = $("<div>").dialog(options);
var id = $(this).data("theId");
dialog.load("the/url/to/the/controller/action", { id: id }, function(){
dialog.dialog("open");
dialog.find("form").submit(function(){
// do stuff
dialog.remove();
return false;
});
});
});
});
</script>
if you are building buttons in a forloop you don't want to define an id on the button. Duplicate id's on a view can cause lots of issues. Use a class on the buttons instead to trigger off of and use $(this) in your script to get details of the button that was clicked. To access buttons on a partial or on items that are added to your page after page load you need to tie the click event for that button to the document like this
$(document).on("click", ".btnDetails", function(){
//your script here
});
The other example uses "this" and shows how you can pass the id of the clicked button back to the controller. The controller will need to be a little different though
public PartialViewResult PopulatePartial(int ID){
var Model = //populate your model based on the passed id
return PartialView("PartialViewName", Model);
}

Categories

Resources