ASP.NET Core - Filling views with data incrementally - javascript

I'm developing a .Net Core application and I have come to part in my code where I need to add data incrementally based on user clicks. First I have a table with elements. Once any element is clicked I need to go and fetch some data from my Entity Framework implementation and based on what I get I should "post" that to the view in a table format.
Then further on the user can click on an element in that new table, and based on the click I need to draw a map with a pointer on it.
I am wondering what is good practice in .Net Core regarding a site like this?
Currently I have a similar-ish view, however only with a single table and a partialView. They way that is implemented is using my site.js to register clicks and HTML elements with data-urls to run my controller methods. Is this the best or most optimal method or is there a smarter way? I really just want to know what types of solutions there are..
I talked with some friends who mentioned they would create a <script></script> section inside their HTML to perform actions like this. I would not nescesarily consider this a best practice for read-ability for code and for fastest possible responses, but I am all ears for other methods for doing this?

Dynamic content
For my opinion the nicest way to add dynamic html code is
Create GET actions in the according controller for getting rendered html-code from partial views (Here you can decide what you want to return)
When some item of your table is clicked, request this actions(with ajax) with the according parameters and return the rendered html data
Insert the HTML with jQuery
Example:
The GET Action
[ResponseCache(NoStore = true, Duration = 0)]
public async Task<IActionResult> NewStamp(string date, string recentProject)
{
// Do work with paramters and evaluate right html-code
return PartialView("_CollectionPartial", new ViewModel(date, recentProject));
}
The HTML-Button
<button asp-controller="Stamps" asp-area="WorkTime" asp-action="NewStamp" id="addStamp" type="button" class="btn btn-success">
<span class="glyphicon glyphicon-plus"></span> Add
</button>
The ajax-request
$.ajax({
url: this.formAction,
data: "date=" + date.format("HH:mm") + "&recentProject=" + recentProject,
cache: false,
success: function (html) {
$('#id').append(html);
Handling .js files
Yesterday I asked a similar question without effort.
But I built my own solution, see this post.

Related

Updating multiple areas with ajax

I've started learning ajax and javascript recently, and still getting a handle on it. But I have a simple goal I'm trying to achieve, and I'm half way there.
For example. I am working on the ability to manage bookmarks saved by one user to be used by other members. I have the code built where I can add, edit, and delete the item live on the page. But how I learned how to do the edit part is a 'click the field area' to start the edit, then 'click out of the field area', to finish the update. I'd really like to change that to a way to click a button to submit the edit.
Also on the page it has a "View Bookmark" button right next to the delete option, but I am not sure how to update that link when I update the text area of it without refreshing the page.
So essentially I want to learn a more efficient way to do live updates via ajax, and then when the update is completed, update all the instances of that same item on the page (which is only two areas).
Any help would be greatly appreciated.
I can post my original code but I think I might be better to learn from someone who knows better. lol
This is a generic question so I will answer generic answer.
If you have, for example, 2 divs
<div id="area1"></div>
<div id="area2"></div>
And you want to call the server and get 2 data's for each div, So it will looks like this: (I'm using jQuery for the example..
$.ajax({
url:'server_url',
method: 'post',
success: function(data) {
$('#area1').html(data.objForArea1);
$('#area2').html(data.objForArea2);
}
});
The JSON that return from the server (for example)
{
objForArea1: '<div class="list-item">item 1</div>...'
objForArea2: '<div class="list-item">item 1</div>...'
}
So you read the response from the object that return from the ajax call, then you put the data wherever you want.

Dropdown based on another dropdown in jsp Struts

I'm very new to Ajax. Currently I'm working on a new project. For that project one of the requirements is, populating a second dropdown based on the input from the first dropdown. I'm using Struts to do that. I don't want the page to be refreshed, so I need to use Ajax for calling the second dropdown content in the backend and populate in the second dropdown. I don't know how to write code for that.
What should be included (jars,tags) in my struts project?
What entries should come in my JSP (I am using <html:select>)?
What will come in JavaScript?
What will come in action class (in action class I can fetch the list values from the DB based on the selection from the first dropdown)?
Instead of ajax, I used struts only to acheive this. I have assigned all variables to form to keep values when submitting form.
The answer to this question would probably a thesis ;)
I will just guide you in here.
1]Use a javascript framework like jquery. It will help you make ajax calls to your controller URL
Check an easy tutorial on http://www.tutorialspoint.com/jquery/jquery-ajax.htm
2] For the controllers lets have two urls mapped:
urapp/poplateDropdown1 to controller which return values/list target at ur first drop down
urapp/poplateDropdown2 to a another controller(or method within same controller) which responds to a GET request and receives a parameter say name SEL_VALUE for the selected value.
3] onchange events.
Have an onchange or similar best suited even on your first dropdoww.
In your event call a js function; like <select onchange=callDropDown2Controller(this.value) >
in your callDropDown2Controller() method:
//pseudo implementation
callDropDown2Controller(var selectedValue){
// now generate an AJAX get request using jquery with the following url
urlToCall = '/urapp/poplateDropdown2?SEL_VALUE=' + selectedValue
}
The rest buddy u need to do some homework and research.

How to make link test if desired page exists, then go to it if it does?

Alright so I am not the most astute javascript/jQuery user, but here it goes.
I want to make a series of html pages that will each link to the next/prev page and will loop once they reach the end of those pages ('page1' and 'lastpage.html'). I know I could do that with just html, but I don't want to have to continually go and revise each page, as I plan on adding pages to that bank/series of pages, so the amount of pages cycling will increase.
The one solution I have thought up of is to test if the 'next' link will exist like this
$(document).ready(function(e) {
$('#next').click(function(){
.preventDefault();
.ajax({
type: 'HEAD',
url: 'art_2.html',
success: function() {
window.location.href = "art_2.html";
},
error: function() {
window.location.href = "art_1.html";
}
});
});
});
So basically how do I make this work, or am I trying to use a tool where I could be using a power-tool?
also added in a prevent default just remembered...
and guess what? Cannot use PHP :/ so yeah...
ALSO I'm kinda lack necessary intelligence to do a good deal of the things with the coding. Entirely self taught...
This is a broken "fix" at most. You should have a server-side script that updates the list regardless of which page you are viewing.
An example of decent implementation would be a mySQL database with a table that contains each page id (auto increment), page url, and optionally a page name. Then dynamically create the "next" and "previous" page based on the results returned form the sql queries.
Keep all pages you want in the cycle/loop in a folder in project
Write a class that reads directory structure
Manipulate file names as you want to link name and store these into a data structure
In UI, based on current page name, get the next one.
I hope this helps.
You could store the data structure in session to access via UI.

Alternative to passing data in onClick?

I have a web page which lists all database records from a certain server.
Along side each row are a few buttons which allow you to rename or delete records.
INPUT( _value='Rename', _type="button", _class='appbutton', _onclick='renameApplication({0},"{1}")'.format(app.id,app.name))
Which generates something like:
<input class="appbutton" type="button" value="Rename" onclick="renameApplication(3,"My Application")"></input>
(The backend templating engine is web2py, but that's not really important.)
I am generating these buttons dynamically. Currently I pass the data each button needs through onClick.
According to jQuery.click() vs onClick I shouldn't be doing this anymore. But if that is the case, how should I be passing data so that each button click can use dynamic data written server side (the application ID and name in this instance.)
I can't do dom traversal through the record to grab the data because the row structure might change.
I can't use custom attributes because I need to support less than HTML 5, and I'm not going to modify the doctype! (Can I add custom attribute to HTML tag?)
The only thing I can think of is to put data in the id attribute then parse it, but that seems very hackish.
Is there a better way?
You may try to use an jQuery on to hook the event on every button. You may put the server Id in an data attribute which is understood by jQuery, without major issues:
<input class="appbutton" type="button" value="Rename" data-id="3"></input>
Then the js:
$('#container').on('click', '.appbutton', function () {
var serverId = $(this).data('Id'); //this binds to html input
renameApplication(serverId);
});

What's the best way to use a YUI TabView in an ASP.NET MVC app?

I'm creating an ASP.NET MVC web app and would like to use the YUI TabView (because I generally like its default look and I'm using a couple other YUI things, so the additional overhead will be comparatively small) to render a set of tabs in the master page. Here's what I want:
Each tab should render the result of a particular controller action.
Each of these controller actions will render some HTML and associated javascript.
Eventually there will be some application state to manage, but I am ignoring that at the moment just to look at the tabbed view.
What's the best way to do this?
The YUI TabView examples suggest that each tab's content is in its own div.
<div id="demo" class="yui-navset">
<ul class="yui-nav">
<li><em>Tab One Label</em></li>
<li class="selected"><em>Tab Two Label</em></li>
<li><em>Tab Three Label</em></li>
</ul>
<div class="yui-content">
<div id="tab1"><p>Tab One Content</p></div>
<div id="tab2"><p>Tab Two Content</p></div>
<div id="tab3"><p>Tab Three Content</p></div>
</div>
</div>
I don't want to do this, since I don't want to load all the content for all the tabs all at once. I'd think I'd like to catch events that let me see the tab that is being activated and then redirect to the appropriate action. It looks like the tabs' "dataSrc" attribute could help me, so I built up a test based on their dynamic example:
tabView.addTab( new YAHOO.widget.Tab({
label: 'One',
dataSrc: '/Home/Action1',
cacheData: true,
active: true
}));
tabView.addTab( new YAHOO.widget.Tab({
label: 'Two',
dataSrc: '/Home/Action2',
cacheData: true
}));
tabView.appendTo('container');
This seems to work well enough in getting to the actions, but one artifact of this is that any javascript that is emitted by my action doesn't seem to get evaluated properly... i.e., this type of thing doesn't show my alert box:
public ActionResult Action2()
{
return Content("<script type='text/javascript'>alert('test');</script>");
}
My concrete questions are:
Should I abandon YUI's TabView because it's just not the best choice for this?
Should I just catch the TabView's onBeforeTabChange event and just redirect to a view that then re-renders the master page (and thus the TabView), basically un-ajaxing the TabView?
Is there a way I can use YUI's TabView and retain the ajax behavior while getting my actions' script code to properly run?
Your content is going to be placed into the page at the appropriate place. The time for its execution is long passed. You need something like jQuery's call back function that will run a script of your choosing after the AJAX action completes. For your alert to pop, you'd have to send it with the original page request.

Categories

Resources