Very new to JQuery and MVC and webdevelopment over all.
I'm now trying to accomplish this and is asking for a bit of advise:
I'm basically trying to build a filter with 4 input elements, and 1 output.
I have 4 select (drop down) elements in my page. As soon as one of them is changed, I need to build a href and get the partial view with the return values.
My question is now if I should try to build the href in the select element or if I can do it once in jquery, and don't have to have duplicated code. How would I accomplish this?
each dropdown should be class="FilterSelect" or something like that
when any of them change, it'll fire off a request to a URL that needs to be specified in a context available to all selects.
the following pseudo-code should give an idea:
$('.FilterSelect').change(function()
{
var data = {} // you need to get the selected items of each dropdown somehow
$.get($(this).parents('#FilterContainer').attr('href'), data, function(response)
{
$('#ContentArea').html(response);
}
});
Just to note: you shouldn't build your URL in jQuery because client-side logic shouldn't be concerned with the rules required to build a URL that corresponds to the server-side routing.
.... & also to note: I don't know if this is even valid jQuery! .parents('#FilterContainer')
You can certainly do it once in jQuery in the modular way you're looking for. Something like:
$('select').bind('change',function(e){
// Our select changed. Send it's selected option's value onwards...
getView(this.options[this.selectedIndex].value);
});
And then, somewhere else:
function getView(url){
$.ajax( url : '/your/url/' + url, success : function(){ }, error : function(){ });
}
Basically, store the URL pieces as values for the options in your dropdowns. Observe the change events and fire off the appropriate request. You can make this as modular as you want (I'd store the URL as a constant, make the whole thing a module, etc.) but this is a good starting point.
Related
Currently I have a view that has just a single form with three values. When a user submits the form with those three values, my controller checks if all three values actually have a value other than being empty, and if they do then it calls my service that fetches data.
public IActionResult Index(string clientName = "", string tableName = "", string date = "")
{
if (!string.IsNullOrEmpty(clientName) && !string.IsNullOrEmpty(tableName) && !string.IsNullOrEmpty(date))
{
// Unimportant stuff for setting temp variables for FetchData parameters removed
TheData = _fieldDataService.FetchData(tempAcr, tempID, tableName, date, numRows);
}
return View(TheData);
}
My goal is to make the view display a loading icon or something while the data is being fetched. I've looked into JQuery and Ajax but I have no experience with either and cannot figure out how to apply them to my specific task. Since I am using Asp.Net Core, I also looked into using Blazor, but I couldn't wrap my head around it either.
Could somebody point me in the right direction as to what I should/could use to solve this problem? I have a vague understanding that there needs to be some sort of asynchronous function that retrieves the data, but nothing more than that.
You need to fetch the data with JavaScript and manipulate the UI to show a loader. But anyway, a request like this should be so fast, that you don't even need a loader.
I'm also a bit worried that you are passing a tableName as input parameter. You aren't just string concatenating the query right? You might be susceptible to SQL injections, see https://en.wikipedia.org/wiki/SQL_injection.
To do a request with JavaScript, look into the XMLHttpRequest, see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest, or the new way of doing it with fetch(...), see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.
This answer shows a more practical example: Display loading image while ajax fetches file content.
I want to know, what's the best way to create a custom back button with parameters?
My example:
I have 4 pages that depend on each other and in these pages I have some actions like updating, deleting, creating and after these actions I need to go back on the last page I was before I am
So I have an ID, which I set on the first page and I have this same ID as the parameter for each page.
If I use the back button of the browser, I will have 2 problems .. 1- If I use it after an action, the browser will redirect to the same page as I am and the second time I click this button it will redirect me to the last page .. 2- will redirect me but no parameters.
And I have an obstacle, I have to clear the URL, so after all '?' I have to clean it, so I use this function:
function cleanUrl() {
urlpg = $(location).attr('href');
urllimpa = urlpg.split("?")[0]
window.history.replaceState(null, null, urllimpa);
setInterval("window.status = ''", 1);
}
Currently, I have this: #Html.ActionLink("","","",new { my parameters })
And this parameters I have an object like:
ObjPreviousPage
{
ID
Filter
Search
}
So, on all of my pages i have this:
#Html.ActionLink("","","", new { ID = x, Filter = "y", Search = "z" })
So I want to know, if have a way to better this or if this way isnt recommended
instead trying to find a hack to do this. I suggest you to rethink your concept how and when is someone redirected to a new URL.
So this could be also helpful to understand the basics
So I have this Action in my asp.net mvc controller which receives an int parameter and returns some json dependent on it. this is how that action looks
Public JsonResult GetSomeData(int intParam)
{
var someData = _someService.GetSomeDataByIntParam(intParam);
return Json(someData);
}
So there is nothing special in here, all the work needed is done by instance of SomeService and then the action just returns the json. this part _someService.GetSomeDataByIntParam(intParam); takes from 35-80 milliseconds on average.
In front-end I have and Jquery code that makes Ajax call to this action and when it gets the answer it just puts the data from json somewhere in the DOM. this is the jquery code (including some razor)
#foreach (var intParam in Model.IntParams)
{
<script type="text/javascript">
$.ajax({
type: 'POST',
url: '/SomeController/GetSomeData',
data { intParam: #intParam },
success : function (response) {
var responseParam = response.param;
if (response.anotherParam)
responseParam += '<span class="some-class">!</span>';
var someForm1 = $('#some-from1-#intParam');
someForm1.children('span.some-another-class').html(responseParam);
var someForm2 = $('#some-from2-#intParam');
someForm2.children('span.some-another-class').html(responseParam);
}
});
</script>
}
There will be on average 3-10 elements int IntParams. that js is executed immediately after the page is rendered. So whole scenario is like this. page is drawn the json data is queried and when its delivered back to js it is inserted somewhere in the DOM. the action which is returning json is queuing other request while it is executing one. so when those, suppose 5 ajax calls are made to the action only one gets executed at a time. (can this be made asynchronous without turning session state off ?) first request gets the answer in 30-80 milliseconds and the fifth gets the answer in 2-2.2 seconds. this is very crucial part in my application so I don't want to lose any milliseconds. I don't understand If the action takes on average 30-80 milliseconds why the fifth one gets the answer in 2 seconds. should not it be something like 400 (5 * 80) milliseconds ? or this call queuing is the thing that is taking too much time ? What can be done to make some optimizations. I image if there were more than 10 calls to execute it would take something like 5 seconds or so. So anyway what can be done to make this whole thing fast. Any suggestion would be appreciated. (even in js code)
I think the model for the current view is having the issue.
Please correct me if this is your current scenario.
You have some kind of single array in Model.IntParams or it may be a list.
for each Item in the IntParams you are sending requests to server.
Suppose if the count of items in 5 or 10, it will send 5, or 10 request and while development or testing it will be fine. Once you have the production data, it can be 100 or 1000s , then you need send that much request.
IIS will process each request by locking the session and we can't say this as a concurrent processing. Check this it may help you jQuery Ajax - Running multiple requests against ASP.NET MVC
Also I will recommend you to have a strong model for the view,with all the properties you need to display. Once you have the strong model fill the data and pass to view.
View only responsible for how the data should display? You can set flags in model , so that you just want to check that condition and decide what to do . Its also makes the code readable and easy to understood by another guy who work with you. I think you can improve your performance by modifying the model and mechanism which fills data to the model.
I have a table of movies and a table of actors managed by a simple CMS built in c#. The user will need to adjust the order of the actors in a list on the movie page. I think the jquery sortable would provide a very nice UI for this and I can implement it on a gridview perfectly well. Code below:
<script type="text/javascript">
$(function () {
$('table').filter(function () {
return $('tr', this).length > 2;
})
.sortable({
items: 'tr:not(:first)',
axis: 'y',
scroll: true
}).disableSelection();
});
</script>
I was also able to grab the new position of a dragged item using code someone shared on the site as follows:
stop: function (event, ui) {
alert("New position: " + ui.item.index());
var x1 = ui.item.index();
}
That second snippet is just to prove I can read the new position, but is not useful for what I need to do.
The actors table has rows with the relevent fields of actorID, movieID and order. When actors are re-ordered in the UI, I need to write the new order values back to the database. This is where I am questioning the best way to do this.
1) Is the sortable widget a reasonable choice in the first place for managing data in a db?
2) If so, what is a smart approach to writing the udpated values back? Performance isn't going to be critical since there are only a handful of users at most, but there could be close to 100 items in the list although the chance are that only one or two would be re-ordered at any time.
1) I've got a page where I do something similar with the jQuery table drag & drop plugin. The user sorts the table by dragging rows around, and we save that order (it gets used in PDF reports and such). If the UI works for your purpose then it's entirely reasonable to use sortable to do that. :)
2) The most straightforward way is that whenever you change the sort order on something, go through the entire list and build an array of the Ids and orders (or even just the Ids in order). You'll then use the jQuery ajax() command to send that array back to the server.
On the server you have a controller action that expects an int array (or whatever you're passing back). You can then save that order to the server. That part is just standard server code, so its pretty easy.
I'd give you some example code, but I don't have time right now unfortunately. :( It's pretty easy to make an ajax call using jQuery though, and there's lots of examples. :)
I stucked at a condition , where i need to share values between the pages. I want to share value from Codebehind via little or no javascript. I already have a question here on SO , but using JS. Still did'nt got any result so another approach i am asking.
So I want to know can i pass any .net object in query string. SO that i can unbox it on other end conveniently.
Update
Or is there any JavaScript approach, by passing it to windows modal dialog. or something like that.
What I am doing
What i was doing is that on my parent page load. I am extracting the properties from my class that has values fetched from db. and put it in a Session["mySession"]. Some thing like this.
Session["mySession"] = myClass.myStatus which is List<int>;
Now on one my event that checkbox click event from client side, i am opening a popup. and on its page load, extracting the list and filling the checkbox list on the child page.
Now from here user can modify its selection and close this page. Close is done via a button called save , on which i am iterating through the checked items and again sending it in Session["mySession"].
But the problem is here , when ever i again click on radio button to view the updated values , it displays the previous one. That is , If my total count of list is 3 from the db, and after modification it is 1. After reopening it still displays 3 instead of 1.
Yes, you could but you would have to serialize that value so that it could be encoded as a string. I think a much better approach would be to put the object in session rather than on the URL.
I would so something like this.
var stringNumbers = intNumbers.Select(i => i.ToString()).ToArray();
var qsValue = string.Join(",", stringNumbers);
Request.Redirect("Page.aspx?numbers=" + sqValue);
Keep in mind that if there are too many numbers the query string is not the best option. Also remember that anyone can see the query string so if this data needs to be secure do not use the query string. Keep in mind the suggestions of other posters.
Note
If you are using .NET 4 you can simplify the above code:
var qsValue = string.Join(",", intNumbers);
Make the object serializable and store it in an out-of-process session.
All pages on your web application will then be able to access the object.
you could serialize it and make it printable but you shouldn't
really, you shouldn't
The specification does not dictate a minimum or maximum URL length, but implementation varies by browser and version. For example, Internet Explorer does not support URLs that have more than 2083 characters.[6][7] There is no limit on the number of parameters in a URL; only the raw (as opposed to URL encoded) character length of the URL matters. Web servers may also impose limits on the length of the query string, depending on how the URL and query string is stored. If the URL is too long, the web server fails with the 414 Request-URI Too Long HTTP status code.
I would probably use a cookie to store the object.