First try to relate the things.
I have a dynamic created div which I was loading from $().Load()
something like this
$(elem).load("BarChart");
Note: elem id dynamically created div at the same moment
untill this all working fine but now I want to send selected Data
something like this
$(elem).load("BarChart",{Values: values});
Note: BarChart is Partial View. which is calling Controller Method but not able to find the values passed from load
controller Method
public ActionResult BarChart(List<String> Values)
{
foreach (var v in Values)
{
lstPointSeries = Utility.GetPointSeries(Session["DbName"].ToString(), Session["AccountGroupName"].ToString(), null, AggregrationType.Total, v, null);
}
ViewBag.pointSeries = lstPointSeries;
return PartialView();
}
Note: Values is null
EDIT:
var values are list of selected checkbox from UI. like this
something like this
values = ["first","second","third","fourth"];
var values = $('input:checkbox:checked.XAxisrowCheckbox').map(function () {
return $(this).closest('td').next().text();
}).get();
I tried your code, and it works fine
Try this:
url = urlHelper.CommonHelper("", "About", "TestAction");
$("#TestDivId").load(url, { Values: ["aaa","bbb"] });
public ActionResult TestAction(List<string> Values) { return View(); }
Related
I have a kendo multi-select widget that is bound to a lot of data, to handle this I have virtualized the widget and put the stress onto the server.
I'm trying to select some initial data via a javascript function that passes an array of Ids. It works well only if the data that's being selected is on the first paged result set of the widget, if any of the Ids are further in then they are not selected and I need to fix it.
Here is the code for my widget:
#(Html.Kendo().MultiSelect()
.Name("Cars")
.DataTextField("Name")
.DataValueField("Id")
.Placeholder("Select cars...")
.Filter(FilterType.Contains)
.DataSource(source => { source
.Custom()
.ServerFiltering(true)
.Events(e => e.Error("errorHandler"))
.ServerPaging(true)
.PageSize(80)
.Type("aspnetmvc-ajax")
.Transport(transport => {
transport.Read("GetData", "Positions");
})
.Schema(schema => { schema
.Data("Data")
.Total("Total")
.Errors("Errors");
});
}))
The data is received from the GetData Method of the Positions controller which is tied to my cars repository.
GetData
public JsonResult GetData([DataSourceRequest] DataSourceRequest request)
{
var car = unitOfWork.CarRepository.Get().OrderBy(n => n.Name);
var results = vessel.ToDataSourceResult(request);
return Json(results);
}
Here is my function that runs after user input (button). I've added a sample array to show you what's passed in.
InitialSelection
function initialSelection(filter) {
//filter is: "6544","4880","6545","6548"
var carSelection = $("#Cars").data("kendoMultiSelect");
var filterArray = filter.split(',').map(Number);
if (filterArray.length > 0) {
console.log(filterArray)
carSelection.value(filterArray);
} else {
carSelection.value();
}
}
Is there a better way to make an initial selection of data than what I'm doing with the above javascript? As I said, if the ids are not on the first page of results that are returned, they are not selected which is frustrating.
You could simply change the read declaration to something like this:
.Transport(transport => {
transport.Read(read => read.Action("GetData", "Positions").Data("intialvalues"));
})
Then add a function for the initialvalues data object like:
function inititalvalues(){
var filterArray = filter.split(',').map(Number);
if(filterArray === undefined || filterArray === null || filterArray.length <= 0)
{
filterArray = []
}
return {filterValues: filterArray};
}
then in your read method on your controller you add the following:
public JsonResult GetData([DataSourceRequest] DataSourceRequest request, List<int> filterValues)
{
if (filterValues.Count > 0 && request.Page == 1)
{
..get the first page minus how many filterValues you have to inject the selected Items at the top of the list...
}
else if (filterValues.Count > 0 && request.Page > 1)
{
..get the page you need and remove any selected items from the page as they will be at the top...
}
else
{
..just get everything as normal as nothing should be selected at this stage.
}
return your paged resultset back...
}
hopefully that gives you a starting point.
I have one WebAPI method which returns IQueryable of a 'complex' object written like this:
[Route("api/INV_API/deptSelect")]
public IQueryable<DEPTNAME_DESCR> GetDistinctDeptSelect([FromUri] string q)
{
if (q != null)
{
var query = (from d in db.DEPTs
where d.DESCR.Contains(q) || d.DEPTNAME.Contains(q)
select new DEPTNAME_DESCR { DEPTNAME = d.DEPTNAME, DESCR = d.DESCR }).Distinct();
return query;
}
else
{
var query = (from d in db.DEPTs
select new DEPTNAME_DESCR { DEPTNAME = d.DEPTNAME, DESCR = d.DESCR }).Distinct();
return query;
}
}
When using AJAX to GET from this method, I receive some sort of javascript array like this:
I have another WebAPI method which I am trying to return a IQueryable<string> form originally a List of string :
[HttpGet]
[Route("api/INV_API/requesterIdSelect2")]
public IQueryable<string> GetListOfUserId([FromUri] string q)
{
var result = db.Database.SqlQuery<string>("SelectUSERIDFromSM #searchterm", new SqlParameter("#searchterm", q)).ToList();
return result.AsQueryable<string>();
}
However, when I inspect what is returned from AJAX GET, it looks like this:
I am trying to understand what I did wrongly in the second method. Do I have to serialise whatever I am returning ? Or is there something wrong with my SQL query itself.
I will provide more information if this is not sufficient.
Update your method like this:
[HttpGet]
[Route("api/INV_API/requesterIdSelect2")]
public IEnumerable<string> GetListOfUserId([FromUri] string q)
{
var result = db.Database.SqlQuery<string>("SelectUSERIDFromSM #searchterm", new SqlParameter("#searchterm", q)).ToList();
return result;
}
IQueryable represent a stored query and not the results returned by query. For executing the query you have to execute method like ToList or Distinct like you have in your first code snippet
The closest I have come to finding an an answer is here: https://stackoverflow.com/a/16295052/608674
The problem is that I can not figure out how set the root name dynamically.
Using the w3widget responsive-calendar. The calendar uses a javascript object with many child objects. Like this:
$(".responsive-calendar").responsiveCalendar({
events: {
"2018-04-30": {
"number": 5,
"badgeClass": "badge-warning",
"url": "http://w3widgets.com/responsive-calendar"
},
"2018-04-25": {
"number": 1,
"badgeClass": "badge-warning",
"url": "http://w3widgets.com/responsive-calendar"
},
"2018-04-03": {
"class": "active special",
"url": "http://w3widgets.com/responsive-calendar"
},
"2018-04-26": {
"number": 2,
"badgeClass": "badge-warning",
"url": "http://w3widgets.com"
},
"2018-05-03": {
"number": 1,
"badgeClass": "badge-error"
},
"2018-06-12": {}
}
});
I attempted to bypass this problem by returning a list of strings from the controller but this isn't working... I'm not sure how to add each string into the "event" JavaScript object with the correct root name.
var jsonEvent = string.Format("'{0}: {{'" +
"'class' : '{1}'," +
"'link' : '{2}'," +
"'link_target' : '{3}," +
"'title' : '{4}'," +
"'location' : '{5}'," +
"'date' : '{6}'," +
"'desc' : '{7}'," +
"'count' : '{8}'," +
"'event_id' : '{9}'" +
"}},",
evnt.StartDate.AddDays(i).ToString("yyyy-MM-dd"),
GetEventClass(evnt.Id, i, dayCount),
evnt.EventUrl,
hasLink,
evnt.Name,
evnt.Location,
dateString,
evnt.Description,
i,
eventId);
I tried to put the string into the event variable like this:
var actionUrl = '#Url.Action("GetJsonEvents", "EventsSurface", new { pageId = Model.Id })';
$.getJSON(actionUrl).done(function (data) {
$.each(data.items, function (index, item) { event[index] = value; });
});
Of course that seems wrong because it would give the root name the value of index.
I've also tried adding the data into variable called "events_data" and parsing it out like was suggested in another question events: Json.Parse(events_data), but that doesn't seem to work... probably because I'm not returning the data correctly from the controller.
It's apparent to me that I just don't understand this process well enough. I know I'm not working with JSON objects so that confuses me when trying to pass back data to the view from the controller...
Assuredly, part of the problem is that I am returning the list of strings from the controller like this: return Json(eventList, JsonRequestBehavior.AllowGet);
I don't know how else to return the data to an ajax call and place it into a JavaScript object.
Edit: 1/518 12.32
Using a Dictionary object in the controller works. I had to create a class for the Json Event Object because the name "class" is reserved in C# and I couldn't use an anonymous object. I ran into a problem trying to decorate the class property with a JsonProperty attribrute...
private class JsonEvent
{
[JsonProperty (PropertyName = "class")]
public string Class { get; set; }
public string link { get; set; }
...}
because I was still using the return Json(..., ...), which is the .net serialization not Newtonsoft. I just had to serialize using Json and return the content: return Content(JsonConvert.SerializeObject(eventList), "application/json");.
In the view, when I JSON.stringify(data) the event object looks perfect. Unfortunately, when I try to use the data in the resonsponive-calendar, it still doesn't work.
So far I have tried:
event_data = data;
event_data = JSON.stringify(data);
Whole ajax call looks like:
var events_data = {};
$.getJSON(actionUrl, events_data).done(function (data) {
console.log(JSON.stringify(data));
events_data = Json.parse(data);
});
And of course, the calendar just calls the event: events_data
Solved 1/5/18 13.54
So, yes, the dictionary in the Controller is the way to go. I am working with someone else's code in JavaScript. They hardcoded the data in. Turns our that the calendar was loading and calling the event data before the ajax call was complete.
so events_data = data works just fine.
Have you tried passing a dictionary from the controller? If that doesn't work, you might have to use a classic ASHX handler and ResponseWrite the JSON object to do what you want.
I'm not sure if returning a Dictionary<string, event> where the date string is the key, from a controller would do what you want or not, but it would be worth a try. JSON isn't hard to ResponseWrite from generic handler either though.
I have an Index.cshtml razor view that lists NewsFeedPosts on it.
In the controller when in the Index() Action Method I am calling my repository initially getting all of the NewsFeedPosts along with their Comments like this:
var newsFeedPosts = _context.NewsFeedPosts
.Include(p => p.Comments)
.OrderBy(t => t.CreatedDate)
.ToList();
In the actual view I am doing something like this to only show the first 4:
<div id="comments">
#foreach (var comment in post.Comments.Take(4))
{
...
}
</div>
Then I will have a link that says 'View additional comments', kind of like how StackOverflow does it.
On Click of this link:
I know I can get this does with an Ajax request calling an action Method called GetNewsFeedPostComments and simply loop through them and append to the #comments div.
However, since I am already retrieving all of the Comments on page load (as shown in the below code) is this really the best way to do this? I feel like there is a better way since I already have all Comments for each news feed post inside of my ViewModel already.
Here is what my pages ViewModel looks like:
public class NewsFeedPostIndexViewModel
{
public IEnumerable<NewsFeedPostViewModel> NewsFeedPosts { get; set; }
}
and when the page initially loads here is how I am populating this ViewModel and sending it to the View:
// GET: NewsFeedPosts
public IActionResult Index()
{
// Get a list of all NewsFeedPosts including comments
var newsFeedPosts = _repository.GetAllNewsFeedPosts();
var newsFeedPostViewModels = newsFeedPosts.Select(fp => new NewsFeedPostViewModel()
{
Id = fp.Id,
Title = fp.Title,
Content = WebUtility.HtmlDecode(fp.Content),
Comments = fp.Comments
}).ToList();
NewsFeedPostIndexViewModel vm = new NewsFeedPostIndexViewModel()
{
NewsFeedPosts = newsFeedPostViewModels
};
return View(vm);
}
So in this JavaScript function is there anyway to utilize what I already have bound in the ViewModel?
$(".lnkViewAdditionalComments").click(function (e) {
e.preventDefault(e);
var newsFeedPostId = $(this).attr('data-newsFeedPost-Id');
// retrieve remaining comments by using skip(4) and loop through them
var comments = #Html.Raw(Model.NewsFeedPostIndexViewModel.Where(f => f.Id = // need to pass JS string here: feedPostId)));
// foreach $(#comments).append(".....");
});
why don't you use grep function in Js
#{
var GetAllComments = Model.FeedPosts.Select(x => x.Comments);
}
<script>
var feedPostId = 1;
var GetCommentJs =#(Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(GetAllComments)));
var filterFata = $.grep(GetCommentJs, function (value, index) {
return value.FeedPostId == feedPostId;
});
</script>
NOTE: you can use also slice function to take limited number of
records after grep.
I have a C# MVC application which is populating a dropdown based on a date selected. Once the date is selected I am sending it to an action via AJAX/jQuery. The action gets a list of items to return for that date.
Here is where my problem is. I have done it previously where I render a partial view from the action and pass it the SelectList as the model. However, I really just want to do it inline in the original view, so I'm hoping there is some way I can return the SelectList and from there do some magic Javascript/JQuery to put it into a dropdown.
Has anybody ever done this before? If so, what do I on the client end after calling the load() to return the SelectList?
I've done something like this previously, when I was just returning a string or other value to be rendered as straight text:
$("#returnTripRow").load("/Trip.aspx/GetTripsForGivenDate?date=" + escape(selection));
But I'm not sure how to intercept the data and morph it into am Html.DropDown() call, or equivalent.
Any ideas?
Thanks,
Chris
Supposing you have a controller action that will feed the data for the dropdown:
public ActionResult Cars()
{
return Json(new[] {
new { id = "bmw", name = "BMW" },
new { id = "mer", name = "Mercedes" },
new { id = "aud", name = "Audi" }
}, JsonRequestBehavior.AllowGet);
}
And in your view:
$.getJSON('/home/cars', { }, function(cars) {
var list = $('select#cars');
list.find('option').remove();
$(cars).each(function(index, car) {
list.append('<option value="' + car.id + '">' + car.name + '</option>');
});
});