Model not updating after jquery ajax post - c#

I'm working on a application which should return multiple list based on selected values.
When a organisation is selected a few queries will run to populate a selectlist.
These queries only return data relevant for the selected organisation.
After that there is a dropdownlist to select which selectlist should be displayed. This will populate another dropdownlist with the data returned from the query.
On the initial load it is loaded correctly for the first organisation. However when another organisation is selected, an ajax post will call a method. this will run the queries succesfully and set the properties to the returned lists. however the problem is that the razor page still uses the data from the initial load.
this results in the fact that whatever organisation i will select, it will use the data from the queries for the first organisation on the razor page.
below the ajax call
$.ajax({
method: "POST",
url: "/Aanleveringen/Create?handler=Filter",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json",
data: { organisatieId: $('#ddlOrganisatie option:selected').val() },
success: function (msg) {
alert(msg);
},
error: function (req, status, error) {
alert("Error try again");
}
});
and the method:
[HttpPost]
public IActionResult OnPostFilter(int organisatieId)
{
Filter filter = new Filter();
Organisatie organisatie = _context.Organisatie.Distinct().Where(x => x.Id == organisatieId).First();
FilterWaardeGemeente = filter.GetFilterGemeente(organisatie);
FilterWaardeDienst = filter.GetFilterDienst(organisatie);
FilterWaardeClient = filter.GetFilterClient(organisatie);
return new JsonResult("Gelukt");
}
looking for any suggestion to have the razor page model update with the most recent c# pagemodel.
thanks in advance.

Changing your model isn't going to do anything, as the Razor page is not being re-rendered. Since you're making the request via AJAX, you need to return your select list items from that action, and then use JavaScript to update the select list options manually in the DOM.

Related

View data from the database

this year I need to build a project on HTML
I choose to build a store so I build a database for all the items (i call it items)
every item has a logo(link to photo), name, price, and description.
and now I want to show all the items on the main page (every single item on an item card)
but! I need to show it Dynamically(That it will only show products that exist in the database)
I try to do it with function with response.write but it did not succeed...
If you can help it would be great!
Create web APIs of return Json type in MVC architecture with C# and include and display the Jquery library in the project.
Jquery library CDN link in;
https://code.jquery.com/jquery-3.6.0.min.js
Example backend code;
public JsonResult AllProduct()
{
var list = db.products.ToList(); //products name table
return Json(list, JsonRequestBehavior.AllowGet);
}
To connect with jquery in html page;
$.ajax({
type: "GET",
url: "AllProduct",
contentType: "application/json",
dataType: "json",
success: function(response) {
$("#table").html(response); //Example #table div show return all value
},
error: function(response) {
console.log(response);
}
});
The database is unknown so let me try to explain the logic. Let me give an example over MVC since you use c# and html tags by definition. In Razor view it will look like below
#foreach(var product in ProductList){
<div>
<div><img src="#product.logoImgConvertedToBase64" /></div>
<div>#product.name</div>
<div>#product.price</div>
<div>#product.description</div>
</div>
}

Getting SQL Data from Dropdown onChange event using ASP.NET Core v2 and Razorpages

I have a dropdown box populated from SQL using C#. When the user select an entry in the dropdown box I need to run a SQL query based on the selected item and populate some other input fields with the resultset from SQL.
Think of it as a list of customers, when selecting a customer the input fields are populated with default values for the customer, such Address, City etc which later can be changed by the user.
My first thought was to use an ajax call on the dropdown onchange event but don't know from where I should get the MSSQL data? is it possible to retrieve data from SQL from an URL? or can I bind the dropdown to the onchange event with C# and add the query data to a script block from C#?
What is a good approach for solving this?
I am using ASP.NET Core v2 with Razorpages
Thanks
Thomas
You should use ajax.
Create an ajax call like this:
var dataToPost = {customer: "custumerValue", additionalData: "something"};
$.ajax("{path to controller}/GetData", {
method: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(dataToPost)
}).done(function (data) {
//set properties
console.log(data.value1);
console.log(data.value2);
}).fail(function () {
//error
});
and in your controller create a function:
public virtual JsonNetResult GetData(string customer, string additionalData)
{
// Get data
return new JsonNetResult()
{
Data = new
{
value1 = "something",
value2 = "something"
}
};
}
Make sure you specify the correct path to your controller, if your controller is named CustomerController you should only insert Customer in the url. Also the name of the function and the parameters must match the names used in the ajax call.
Hope this helps.

Best option for a editable dropdown

I want a dropdown menu that allows user to type in text..something like autocomplete with dropdown.
I have been trying this for a long time now and while going through other posts I found people suggesting Ajax but I could not use it.
What are the other options available ?
also,I have to bind the dropdown to a database query so the option must allow that.Thanks a ton!
you can try one of these two :
Chosen
Select2
Try using this code:
$("#DropDOwnID").select2({
ajax: {
url: "https://graph.facebook.com/v2.2/search", //method which returns the data for select2 OR in web forms use web service
type: 'GET',
multiple: true, //if dropdown can have multiple or not
dataType: 'json',
delay: 250,
data: function (params) {
return {
parametername: params.term, // search
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
var myResults = [];
$.each(data.data, function (index, item) {
myResults.push({
'id': item.key,
'text': item.name
});
});
return {
results: myResults
};
},
cache: true
},
minimumInputLength: 1,
});
You can try Select2 https://select2.github.io/
It has Ajax \ plain HTML mode, as well as ability to create pagination for large quantity of items.
You can create it using plain select as data source or even hidden input for ajax \ pagination

How do I pass the string value parameter of the selected list item from an auto-populated dropdown list to a partial view controller in MVC 4?

I have created an auto-populated drop downlist on my MVC 4 web application. When the user selects an item from the dropdown list, I want the partial view to show the item selected rather than all items as it already displays in this partial view.
How do I pass the string value parameter of the selected list item from an auto-populated dropdown list to a partial view controller?
Here is the code for my auto populated dropdown list:
#foreach (var m in ViewDatamodel)
{
if (m.State == "In Work")
{
<li>#m.TargetName</li>
}
}
I want to pass the m.TargetName string as a parameter so that i can manuipulate the partialview based on which list item is selected. The partialview consists of progress bars for jobs being performed where the data is stored on a SQL Server DB. I use the following Ajax Script to refresh the original partial view every 3 seconds. I need to be able to do the same with the selectedd partial views. Again, this is all autopopulated, so I am assuming the best way is to go by the TargetName:
<script>
function loadpartialView() {
$.ajax({
url: '#Url.Action("_GetfoeStatus', "Status")',
type: 'POST',
data: '{}', //I am assuming that I will need to pass the parameter to here
cache: 'false',
async: 'true',
success: function (result) {
$('#progress').html(result);
}
});
}
$(function() //..... Refresh Timer
Both the Action and RenderAction methods have overloads that allow you to pass additional parameters that are appended to the query string for the resource.
If you are doing this on the server side, you can:
Html.RenderAction("_GetForStatus", "Status", new { TargetName = m.TargetName })
If you are doing this on the client side, you would have to write some additional jQuery to make it work (or just plain old Javascript).
function loadpartialView() {
$.ajax({
url: '#Url.Action("_GetfoeStatus', "Status")',
type: 'POST',
data: { TargetName: $("#YourDropDown").val() }
cache: 'false',
async: 'true',
success: function (result) {
$('#progress').html(result);
}});
}
I used "TargetName" because I didn't know what your parameter name is.

How to call an MVC Action using only JavaScript?

I have this Kendo UI dropdownlist with a select event that is handled by a JavaScript function.
I need to call an action result from a controller that runs a LINQ query to populate a Kendo UI grid on my page. My problem is the only way I can find to handle this even is with JavaScript and I have been unable to figure out how to call my action result from my controller from the JavaScript event function.
This is what the DropDownList looks like...
#(Html.Kendo().DropDownList()
.Name("Options")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Policies Not Archived",
Value = "1"
},
new SelectListItem() {
Text = "View All Policies",
Value = "2"
},
new SelectListItem() {
Text = "Filter Policies",
Value = "3"
}
})
.Events(e =>
{
e.Select("select");
})
)
and my JavaScript event handler that needs to call the action result
function select(e) {
}
and depending on the selection an ActionResult like this,
public ActionResult ViewAllPolicies()
{
//mycode
}
see this post
var url = '#Url.Action("ViewAllPolicies","YourController")';
$.ajax({ url: url, success: DataRetrieved, type: 'POST', dataType: 'json' });
in controller
public ActionResult ViewAllPolicies()
{
//Should return json format
}
url – this is the URL where request is sent. In my case there is
controller called contacts and it has action calles
ListPartiesByNameStart(). This action method takes parameter
nameStart (first letter of person or company). success – this is the
JavaScript function that handles retrieved data. You can write there
also anonymous function but I suggest you to use functions with names
because otherwise your code may get messy when functions grow. type –
this is the type of request. It is either GET or POST. I suggest you
to use POST because GET requests in JSON format are forbidden by
ASP.NET MVC by default (I will show you later how to turn on GET
requests to JSON returning actions). dataType – this is the data
format that is expected to be returned by server. If you don’t assign
it to value then returned result is handled as string. If you set it
to json then jQuery constructs you JavaScript object tree that
corresponds to JSON retrieved from server.
Instead of returning json, you can also return a PartialView and in the .done function grab an element and replace it with the results from the partial view. PartialView actions basically return a fragment of HTML, and so you can just stuff that anywhere you want on the page:
$.ajax({
url: urlToPartialViewAction,
type: 'POST',
dataType: 'JSON',
data: '123'
})
.done(function (result) {
$('#someDivPlaceholder').replaceWith(result);
});
You could have something like a link or grey div and wire up to it's click event and then call this, the link might say "View Receipt" and when you click it you call an action that returns a partial view with the receipt, and so when they click it the div/link is replaced with the result. Kind of like the "View More Comments" links you see on social sites.
Note that you can't have a partial view by itself, it must be called through an action
public PartialViewResult _GetReceipt(string id)
{
ReceiptViewModel vm = //query for receipt data
return PartialView(vm);//render partial view and return html fragment
}
Once the select function executes, you need to make an AJAX call back to your Controller. You can use jQuery.ajax() (a wrapper for the most common AJAX operations) in the select function,
function select(e) {
var url = '#Url.Action("ViewAllPolicies", "PolicyController")';
var selectedPolicy = $('#Options').val(); // The option selected
$.ajax({
url: url,
type: 'POST',
dataType: 'JSON',
data: selectedPolicy
})
.done(function (data) {
// Display the data back from you Controller
});
}
You can look at the Kendo site for more info on how the DropDownList works.

Categories