How can I use jqGrid along with textbox to search? - c#

My data is being correctly loaded on my page. However I have 2 textboxes and one submit button based on which I want to filter the records from the server.
Note: I am not using existing filters functionality that is available with jqgrid by default.
I am little confused how can I achieve this. Is there any built in capability of jqgrid to achieve this? The way I currently handle this is I handle the click event in my javascript and supply post data to the action method:
$('#submit').click(function () {
$("#customers").jqGrid('setGridParam', { postData: { 'ContactName': $('#contactName').val(),
CompanyName: $('#companyName').val()
}
});
$("#customers").trigger("reloadGrid");
});
This post data is then being captured on action method and it works fine. Is there any better way of doing this? or am I on right track? Sometimes I feel I write less code on the server and have become more of a client side programmer since I started using Asp.Net MVC 3.0 ;)

You don't have to use setGridParam to change postData as you can declare a function :
jqGrid({
url : ...,
datatype : ...,
mtype : "POST",
postData : {
"ContactName" : (function() {
return $("#contactName").val();
})
}
}
so your submit function will only call to reloadGrid
$('#submit').click(function () {
$("#customers").trigger("reloadGrid");
}
If you want to reduce the amount of code, and you'd better create a simple API in JS to select entities like Customer, Person, Contact etc. Currently I have an app which forms consist of dozens such entities - so I had to create an JS API for selecting(it also gives universal look and feel). From the client side the customer specifies the name of list to get, while the list of possible names is defined in the server's configuration file, which also defines the query to the ORM and how to display fields(I am using an expression language to map from entity fields to strings).

Related

ASP.NET Core Web App - Dynamic form values passed to OnPost

I'm creating an ASP.NET Core Web App with .NET 6 and I'm trying to find a way to pass a dynamic list of variables back to the OnPost handler. Here's the details, I create a form on the page during the OnGet. I don’t know how many fields, or the types, this form will have at design time. It can be as few as one or as many as 20. They could be text fields, dates, integers, checkboxes, etc., but I don't know ahead of time. When the user submits this form, I need to collect all the values in the OnPost and display the results; the results are also dynamic but that's a separate issue. So how do I get the values? I can't create BindProperties or create a Model, ‘cause I don't know how many or what they are. I can easily assign a unique Id/Name to the form while I'm building it, Param1, Param2, Param3, etc. but that's not the important part. I can't imagine that I'm the first person to attempt this, but I can't find any examples of how to accomplish this, at least in Asp.Net Core .NET6
Since you aren't using model binding you can access the form data directly and loop through all the data
var formData = Request.Form;
foreach(var data in formData)
{
// Name attribute from the form
string keyName = data.Key;
// Value the user entered
string keyValue = data.Value;
}

MVC - Retain model result for use in ajax method without passing in via JSON?

Long time lurker first time posting, so hey!
TL:DR - how would I keep a value from the original page-loading-controller to the ajax method without passing it in as a json object as part of the ajax request? And I can't use Session[]!
Backstory - I'm working on a filter-search functionality which brings back a big list of objects on the initial page load, generated from a database call and populates Model.FullResults.
In order to filter the results, rather than keep doing more database calls each time a filter is clicked, I'm simply filtering the results via linq in an AJAX method, like so:
var fullResults = #Html.Raw(Json.Encode(Model.FullResults));
var obj = {
//filter tickboxes statuses etc are here
fullResults: fullResults
}
var jqxhr = $.ajax({
//urls etc removed for clarity
data: JSON.stringify(obj),
success: function (response) {
//stuff
}
}
});
Which is all working perfectly fine for small values of Model.FullResults. However, if Model.FullResults is pretty large (i.e. on my main search page), this is a large amount of data to pass across via ajax each time, and the only reason I'm even passing it across this way is just for the plain and simple fact of I don't know how else I can "keep" this data from the original controller action and still have it for use the ajax method.
Storing Model.FullResults in Session was a brief thought, but there's a high probability people will open multiple tabs that hit the same controller, thus making session outdated. Something like Viewdata would be ideal but I can't access that in the ajax method of course.
So how would I keep this value for use in the ajax method? Do I have to resort to doing another database call OR passing it into the ajax method? There must be a way of retaining it somehow?
Thanks in advance you helpful bunch! :)
You can go for memoryCache to save large amount of data. Similer problem was with me where I have to read data from csv file and pass through Web API. Every-time, reading data from text was not a good idea, So I saved data in memory cache and fetching the records from memoryCache to avoid reading from stream. A simple demo is shown on my github account.you can co relate it.
https://github.com/abhee235/SimpleRestfulAPI/tree/master/DataProvider
Note : The project is not optimized for performance point of view. It is just a demo.

How to link schema in "GraphQL for .NET" and "Relay"?

I want to build a web app with Javascript for the front end and C# for the back end and I want to determine the value of GraphQL.
For my C# back end I use a GraphQL implementation named GraphQL for .NET.
For my front end, I would like to use Relay as it plays well with ReactJS.
Now for my back end, I implemented a sample schema like in one of the examples which looks like this:
public class StarWarsSchema : Schema
{
public StarWarsSchema()
{
Query = new StarWarsQuery();
}
}
In my front end, I now need to tell Relay somehow about this schema. At least this is what I understood when walking through the tutorials, because for some reason the GraphQL queries needs to be transpiled.
This is an example as how I would like to load all Droids:
class Content extends React.Component<ContentProps, { }> {
...
}
export default Relay.createContainer(Content, {
fragments: {
viewer: () => Relay.QL`
fragment on User {
query HeroNameQuery {
droids {
id
name
}
}
}
`,
}
});
In one of the examples for Relay, I have seen that the babel-relay-plugin is used for conversion. It gets a schema file (JSON). The Getting Started Guide of Relay shows, how to create such a schema with graphql-js and graphql-relay-js.
Now my questions:
Do I really need to create schemas on the front and on the back end?
What is the point of teaching Relay my schema, as the back end already uses the schema to return the well formed data?
What is the benefit at all from using Relay in this scenario? What would I lose when I would just access the backend via a regular REST endpoint along with a GraphQL query as a parameter?
You need schema only on the backend and you can download schema.json from your backend using example at the bottom part of this document: https://facebook.github.io/relay/docs/guides-babel-plugin.html
Relay need schema to correctly construct queries and understand types of returned data.
Relay wraps your React components and fetch/provide all necessary data for rendering. Have many features out of the box like data caching, query consolidation, so with Relay you don't need to fetch anything and worry about how data provided to your component, you just need to write queries and components.

How to pass nested parameters in REST api's for Get

I have the following scenario.
There are few Events and each event is represented by group of friends.
1st i request a list of events which is achieved using simple Get request.
http://example.com:6400/api/Events/
Corresponding Rest API : public IEnumerable<Event> Get();
Now i can search the event list and can request for a particular event say (event 5)
http://example.com:6400/api/Events/eventdetail/5.
Corresponding Rest API : public HttpResponseMesssage eventdetail(int id);
But now if i want to receive info about a particular friend(say friend's id is 10) in that event(5) i am unable to find a way. One way i was able to achieve is using a comma separated
Get request:
http://example.com:6400/api/Events/eventdetail/5,10.
Corresponding Rest API: Not Sure ????
But i don't think this is the best way to do it. Is there any ways through which i can achieve the desired result and corresponding Rest API.
Just start accepting two parameters in your method:
public HttpResponseMesssage EventDetail(int id, int friendId) {
//Do your stuff!
}
The corresponding URI would look like:
http://example.com:6400/api/Events/EventDetail/5?friendId=10
Notice how the HTTP parameter name matches the C# method name. For more information about ASP.NET MVC routing I would suggest reading their overview.

ASP.NET MVC Data Feedback through User Controls

In our new product we have a few data entry fields that require you to search for the correct value to place in this field.
When you enter this data entry field I would like to provide a search option via something on the view (perhaps an Ajax implementation) and have it allow searching of the database for the value, but when the result returns I want to keep the existing values in place for other fields not affected by the search.
But I have no idea how to do this with MVC. Does anyone have any suggestions on how this should be done?
Write your data entry page in the
usual way for an ASP.NET MVC view.
Get it working without the Ajax
(e.g., submit works correctly when
you just type in the values, without
auto complete).
Write the prototype for a JavaScript method you'll called when the user performs a certain action (e.g. presses a key inside of a certain control). But this inside a script tag in your aspx page. Unfortunately, stack overflow seems to "sanitize" script tags in my example, so I can't demonstrate that part. But you're JavaScript prototype will look something like this:
function startAutoComplete() {
}
Now hook up the event handlers on the user interface control. You need to call the function you've just prototyped an appropriate event handlers for your application. From your description, it sounds like you might want to use onkeydown, but there are lots of events to choose from. You probably need to handle more than one event, as appropriate for your application.
So far, everything that we've done has been standard aspx and JavaScript. In this step, we'll do the only part of the whole process which is really different for ASP.NET MVC. You need to add an action to your controller which will be called (indirectly) by the JavaScript prototype you've just written. The action should accept appropriate input (e.g., a string representing the text from control, or something like that, as appropriate for your application) and return its results in JSON format. I'm going to show a really simple example here; feel free to substitute more complex code in your real application.
public ActionResult GetSuggestions(string searchText)
{
return Json(new {SearchText = searchText});
}
This example just returns a JavaScript object containing one property, which contains the value passed to the function. Like you said, you can write something more useful for your application.
Now you need to call this function in JavaScript. The URI will look something like:
http://localhost/mycontroller/GetSuggestions?searchText=Foo
It is possible to make Ajax calls without a JavaScript library, but much easier if you use jQuery or some other library which handles cross-browser compatibility issues for you. Since I happen to like jQuery, I'll demonstrate that. Let's update the startAutoComplete method we prototyped earlier:
function startAutoComplete() {
var searchText = $("#myeditorid").text();
$.getJSON("/mycontroller/GetSuggestions?searchText=" + searchText,
null,
autoCompleteResponse);
}
The first line uses jQuery to get the text in the control with the ID myeditorid. We'll pass this to the ASP.NET MVC action as the searchText argument, by appending it as a query string parameter.
The next line, which starts with $.getJSON calls a jQuery function which makes an Ajax call to the URI you specify. We pass an argument, autoCompleteResponse, which is the name of a JavaScript method to be called if the response from the Ajax call is successful. Now we have to write autoCompleteResponse.
function autoCompleteResponse(data) {
if (data.SearchText)
{
$("#myeditorid").text(data.SearchText);
}
}
This says, "If the data returned has a SearchText property, set the text of the control to that value." Again, do whatever is appropriate for your application with the data returned.

Categories

Resources