Grid not updating after ajaxcall - c#

I'm creating my own filter. The filter has a dropdownlist, when this dropdownlist changes jquery will make an ajaxcall to the corresponding HTTPPOST - controller action. In this action I filter the list and pass it through to my view.
Once the list has reached my view, the webgrid is not updating. Here is some code with some debug information to show what's happening.
Controller
normal action
public ActionResult Projects()
{
IEnumerable<Project> projects = Adapter.ProjectRepository.Get();
int test = projects.Count();
List<ProjectsDisplayViewmodel> projectsView = new List<ProjectsDisplayViewmodel>();
string strCats = "";
foreach (Project prj in projects)
{
strCats = "";
Mapper.CreateMap<Project, ProjectsDisplayViewmodel>();
ProjectsDisplayViewmodel newProject = Mapper.Map<Project, ProjectsDisplayViewmodel>(prj);
foreach (Category cat in prj.Categories)
{
strCats += cat.CategoryName + ", ";
}
newProject.strCategories = strCats;
projectsView.Add(newProject);
}
ViewBag.Categories = new SelectList(Adapter.CategoryRepository.Get(), "CategoryID", "CategoryName");
/*projectsview contains 4 projects now*/
return View(projectsView);
}
httppost action
[HttpPost]
public ActionResult Projects(string catID, string strSearch)
{
IEnumerable<Project> projects = Adapter.ProjectRepository
.Get()
.Where(x =>
x.Categories.Any(
c =>
c.CategoryID == Convert.ToInt16(19))
);
int test = projects.Count();
List<ProjectsDisplayViewmodel> projectsView = new List<ProjectsDisplayViewmodel>();
string strCats = "";
foreach (Project prj in projects)
{
strCats = "";
Mapper.CreateMap<Project, ProjectsDisplayViewmodel>();
ProjectsDisplayViewmodel newProject = Mapper.Map<Project, ProjectsDisplayViewmodel>(prj);
foreach (Category cat in prj.Categories)
{
strCats += cat.CategoryName + ", ";
}
newProject.strCategories = strCats;
projectsView.Add(newProject);
}
ViewBag.Categories = new SelectList(Adapter.CategoryRepository.Get(), "CategoryID", "CategoryName");
/*projectsview contains 1 project now AND WILL DISPLAY 4*/
return View(projectsView);
}
project.cshtml
#model IEnumerable<Freelauncher.Models.ProjectsDisplayViewmodel>
#{
ViewBag.Title = "Projects";
}
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 25,
selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.NextPrevious);
}
<h2>Alle projecten</h2>
#Html.DropDownList("Categories", (SelectList) ViewBag.Categories)
<div id="gridContent">
#grid.GetHtml(
columns: grid.Columns(
grid.Column("ProjectTitle", "Titel"),
grid.Column("ProjectDeadlineDate", "project deadline"),
grid.Column("ProjectEndRegisterDate", "Registreer deadline"),
grid.Column("ProjectBudget", "Prijs"),
grid.Column("ProjectIsFixedPrice", "Vaste prijs"),
grid.Column("strCategories","Categorieën"),
grid.Column("ProjectID", "meer info", format: (item) => Html.ActionLink("info", "project", new { Id = item.ProjectID} ))
//grid.Column("ProjectID", "meer info", format: Html.ActionLink("info", "project", new { Id = }
))
</div>
What am I missing that the project list in my view is not updated, the correct data is passed to the view....
edit
The ajax call
$("#Categories").change(function () {
var param = $(this).val();
$.ajax({
type: "POST",
url: "/Project/Projects",
data: { catID: $(this).val(), strSearch: 'test' },
dataType: "json",
success: function (response) { console.log("succes"); },
error: function (xhr, ajaxOptions, thrownError) {console.log("error"); }
});
});
I just noticed that nothing is printed in my console.log.... Not the success neither the error function.

You don't seem to be doing anything in the success callback of your AJAX request (other than a console.log call). So it's perfectly normal that nothing updates. You need to manually update your DOM if you want this to happen.
So you should modify your HttpPost controller action so that it returns a PartialView containing the grid. And then in your success callback inject the newly received partial into the DOM:
success: function (response) {
$('#some_id_of_a_containing_div').html(response);
console.log("succes");
},
In this example you should wrap the partial view into a containing div which will get updated here:
<div id="some_id_of_a_containing_div">
#Html.Partial("Partial_Containing_Your_Grid")
</div>

Related

I want to use C# distinc how can I do

I have select2s, I fill these select2 with procedure. I fill select2 by saying return json on the controller side. But repetitive recordings are coming, where can I use DISTINCT for this?
JavaScript
$('#markaSelect').select2({
ajax: {
url: '/Home/MarkaGetir',
data: function (params) {
var query = {
q: params.term,
ModelAd: $('#modelselect').val(),
UreticiAd: $('#ureticiselect').val()
}
return query;
},
dataType: 'json',
type: "POST",
},
placeholder: 'Marka Seçiniz',
allowClear: true
});
Controller
public JsonResult MarkaGetir(string q = "", string MarkaAd = "", string ModelAd = "", string UreticiAd = "")
{
var lst = Vtİslemleri.Mmu(MarkaAd, ModelAd, UreticiAd);
lst.Select(x => x.Marka).Distinct();
return Json(new
{
results = lst.Select(x =>
new
{
id = x.Marka,
text = x.Marka
})
});
}
A short example: There are 4 of the Seat brand models, I want 1 to come when I shoot this.

asp.net Razor Pages - Update select list based on the selection of another select list

I want to update a select list when the user selects a value in another select list. I've managed to get the first select list to call a get (or post) method on the model with a parameter, and can update the underlying data. But the second select list never shows the new values.
I'm not very experienced with asp.net, so what am I doing wrong?
Code below
.cshtml
<div>
<form method="post">
<select id="departureStation" asp-items="Model.DepartureStations" onchange="getDestinationStations()"></select>
<select id="destinationStation" asp-items="Model.DestinationStations"></select>
</form>
</div>
#section Scripts {
<script type="text/javascript">
function getDestinationStations() {
var selectedDepartureStationID = $("#departureStation").find(":selected").val();
console.log("selectedDepartureStationID = " + selectedDepartureStationID);
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
console.log("success - " + result);
},
error: function() {
console.log("failure");
}
})
}
</script>
}
.cs
public List<SelectListItem> DestinationStations
{
get
{
if (this._selectedDepartureStationID == -1)
return new List<SelectListItem>();
List<Models.Station> stations = new List<Models.Station>();
List<Models.RouteSegment> routeSegments = this._context.RouteSegments.Where(x => x.StationID == this._selectedDepartureStationID).ToList();
foreach (Models.RouteSegment routeSegment in routeSegments.DistinctBy(x => x.RouteID))
{
List<Models.RouteSegment> routeSegments2 = this._context.RouteSegments.Where(x => x.RouteID == routeSegment.RouteID).Include(x => x.Station).ToList();
stations.AddRange(routeSegments2.Select(x => x.Station));
}
return new List<SelectListItem>(stations.Distinct().ToList().Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList());
}
}
public IndexModel(MyViewContext context)
{
this._context = context;
}
public void OnGet()
{
this.DepartureStations = this._context.Stations.Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList();
}
public IActionResult OnGetDeparture(int selectedDepartureStationID)
{
this._selectedDepartureStationID = selectedDepartureStationID;
return Page();
}
Whenever your #departureStation select changes, your code will call getDestinationStations javascript code. Inside that function you are sending a request to your backend server to receive possible destination stations if I understood correctly. What you need to do here is when ajax request successes, add options dynamically based on your returned array or data.
I am assuming your "/Index?handler=Departure" returns a JSON like:
[
{
id: 1,
name: "station1"
},
{
id: 2,
name: "station2"
}
]
Check if code below works.
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
let destinationStationSelect = $('#destinationStationSelect');
let optionTemplate = $('<option></option>');
$.each(result, (index, element) => {
let option = optionTemplate.clone();
option.append(element.name);
option.attr('value', element.id);
destinationStationSelect.append(option);
});
},
error: function() {
console.log("failure");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Data from view to controller to view

I am trying to get the data of a hidden textbox from the index to a textfield in another view.
First, I get the data using AJAX.
//ajax
if (id && toolcode && shopdoccode) {
$.ajax({
type: 'GET',
url: '#Url.Action("delivery", "service")',
data: { id, memo },
success: function (data) {
if (data.success) {
console.log("Succes");
window.location.href = '#Url.Action("delivery", "service")';
}
},
error: function (data) {
console.log("Error");
}
});
}
window.location.href = ("service/delivery?id=" + id + "&toolcode=" + toolcode + "&regdate=" + regdate + "&shopdoccode=" + shopdoccode + "&memo" + memo);
}
Then, I make a viewbag in the controller to pass the data to my other view.
public ActionResult Delivery(string id, string memo)
{
ServiceOrder service = GetService(id);
ViewBag.id = id;
ViewBag.memo = memo;
And finally, in the view
#using (Html.BeginForm("GeneratePDF", "Service", FormMethod.Post, new { #class = "form-style-4", id = "getPDFForm" }))
{
string memofield = ViewBag.memo;
//code
<textarea name="jobdescription" readonly>#memofield</textarea>
if I set breakpoints in the controller, I can see that Viewbag.memo contains the correct data. Once in the view I've set a breakpoint on the string memofield = viewbag.memo
Even there, I can see the data. but then, suddenly, if I press continue, the strings are back to 'null'
What am I missing here?
It can happen because after you send ajax request you are redirecting back to Delivery action window.location which does not contain post parameters id and memo.. see
success: function (data) {
if (data.success) {
console.log("Succes");
window.location.href = '#Url.Action("delivery", "service")';
}
}

Ajax not updating my search list

I'm using MVC 5 C# and I'm trying to update my search filter on key strokes through AJAX. By code it works but the results aren't showing up on testing. I've done some debugging and in my view the results are being thrown in the view as shown:
It's supposed to be displayed right underneath the search box but shows nothing.
Not quite sure what the issue is. So I'll list my code. Here is my Ajax.
<p>
Search Employee: <input type="text" name="userName" onkeyup="filterTerm(this.value);" />
</p>
<script>
function filterTerm(value) {
$.ajax({
type: "POST",
url: '#Url.Action("Index", "Directory")',
data: {
userName: value
},
cache: false,
success: function (result) {
}
});
}
</script>
Ajax has been tested and is working, now in my controller it also is returning results (obviously is being pulled back to the View but just showing results).
But here is my controller anyways:
[HttpPost]
public ActionResult Index(string userName)
{
/**********Establish Connection********/
DirectoryEntry dir = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(dir);
/****Refer to class constructor****/
/********Create the List to store results in***************/
List<ADUser> Users = new List<ADUser>();
string DisplayName = "", SAMAccountName = "", Mail = "", Description = "", Department = "", TelephoneNumber = "", Fax = "";
/*******Filter parameters************/
search.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(anr=" + userName + "* ))";
SearchResultCollection searchresult = search.FindAll();
search.PropertiesToLoad.Add("Displayname");
search.PropertiesToLoad.Add("SAMAccountName");
search.PropertiesToLoad.Add("Mail");
search.PropertiesToLoad.Add("Description");
search.PropertiesToLoad.Add("TelephoneNumber");
search.PropertiesToLoad.Add("Fax");
search.PropertiesToLoad.Add("Department");
/*****************Filtering and populating the List****************/
if (searchresult != null)
{
foreach (SearchResult iResult in searchresult)
{
ADUser userAttributes = new ADUser("", "", "", "", "", "", "");
foreach (string PropertyName in iResult.Properties.PropertyNames)
{
foreach (Object key in iResult.GetDirectoryEntry().Properties[PropertyName])
{
try
{
switch (PropertyName.ToUpper())
{
.....
}
}
catch { }
}
}
Users.Add(userAttributes);
}
return View(Users);
}
return View();
}
It seems like it might just be something I'm missing that I don't know about.
Any help would be greatly appreciated.
Cheers
serialize your user list to json before return it to view as follow.
using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(User);
return View(json)
and make your ajax's datatype json as follow :
$.ajax({
type: "POST",
url: '#Url.Action("Index", "Directory")',
data: {
userName: value
},
dataType:"json",
cache: false,
success: function (result) {
}
});

How get value from cascading drop down list made with ajax

I am very new to MVC, and am try to set up a series of cascading drop down lists using this example.
But I am stuck a little bit, because I don't know how to get the value from the second drop down and send it to controller when I press the appropriate button.
Here is my view:
<script type="text/javascript">
$('#list').change(function() {
var selectedClient = $(this).val();
if (selectedClient != null && selectedClient != '') {
$.getJSON('#Url.Action("SelectC")', { clientID: selectedClient }, function (client) {
var campaingSelect = $('#clist');
campaingSelect.empty();
$.each(client, function(index, clients) {
campaingSelect.append($('<option/>', {
value: clients.value,
text: clients.text
}));
});
});
}
});
</script>
#using (Html.BeginForm("CreateNewCampaign", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.LabelFor(m => m.alreadyCreatedCampaignName, "Name:")
#Html.DropDownList("clist","-- Select Client -2-")
<input type="Submit" name="button" value="Select" class="btn btn-primary" />
}
Controller:
public ActionResult SelectC(int clientId, CampaignModel model, FormCollection form)
{
Session["ClientID"] = clientId;
ViewBag.ClientName = "You're using: " + Session["ClientName"];
var CampaignInf = CampaignManagementService.GetCampaigns((string) Session["ticket"], clientId);
List<AlreadyCreatedCampaignList> itemas = new List<AlreadyCreatedCampaignList>();
foreach (var element in CampaignInf)
{
itemas.Add(new AlreadyCreatedCampaignList() {CampId = element.Key, CampName = element.Value});
}
var listOfCam = new SelectList(itemas, "campID", "campName", 1);
return Json(listOfCam.Select(x => new {value = x.Value, text = x.Text}), JsonRequestBehavior.AllowGet);
}
I want to get the value to other controller, and I am not sure of the right way to go about doing this.
You can get value of dropdownlist just by giving it ID and call $("#id").val();, then you can transfer it to the controller through ajax maybe.
Here is mine, try it
public ActionResult ActionName(string dropdown_value){
//your code
}
<script>
$(document).ready(function(){
$("submit").click(function(){
$.ajax({
url:"Controller/ActionName",
datatype: "POST",
data: { dropdown_value : $("#clist").val() },
success : function(){ //your code if success }
});
});
});
</script>

Categories