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>
}
Related
i have bind drop down using WebMethod (Services)
I have multiple drop down list and need to bind on mutully dependent to each other like cascading of dropdown list but while passing value for one selected vale its showing null while debugging on my web method
WebMethod:
public static List<Company> GetCompanies(string CountryCode, string CompanyCode)
{
GetInitiatorList.MasterDataServiceClient oClient = new GetInitiatorList.MasterDataServiceClient();
Almarai.GiveAway.GetInitiatorList.ALM_COMPANY_M[] initiatorsList = oClient.GetActiveCompanies(CountryCode, CompanyCode) List<Company> Companyes = new List<Company>();
foreach (Almarai.GiveAway.GetInitiatorList.ALM_COMPANY_M company in initiatorsList)
{
Companyes.Add(new Company()
{
CountryCode = company.CompanyCode,
CompanyName = company.CompanyName
});
}
return Companyes;
}
JQuery
$('#ddlCountry').change(function (e) {
var selectedCountry = $('#ddlCountry').val();
$.ajax({
type: "POST",
url: "Header.aspx/GetCompanies",
data: JSON.stringify({ CountryCode: selectedCountry, CompanyCode: 'SAU' }),
dataType: "json",
contentType: "application/json",
success: function (res) {
$.each(res.d, function (data, value) {
$("#ddlCompany").append($("<option></option>").val(value.CompanyId).html(value.CompanyName));
$('#ddlCompany').change(function (e) {
Aspx:
<div class="col-md-8">
<select id="ddlCountry">
<option value="0">--Select Country--</option>
</select>
</div>
Where i am doing wrong Please guide me
To get the currently selected value from dropdown:
$('#ddlCountry').val();
To get the currently selected text from dropdown:
$('#ddlCountry :selected').text();
You can check first your ajax call is working properly or not , by sending hard coded text by specifying like this in ajax call:
$.ajax({
type: "POST",
url: "Header.aspx/GetCompanies",
data: JSON.stringify({ CountryCode: 'USA', CompanyCode: 'SAU' })
....
Then you can check are you assign dropdown values properly or not ? If you only want text not value then you can use as I have mentioned on top. I think it will solve your problem. Please let me know if it isn't.
============ Updated (after reading comments) ======================
I have created a sample demo based on your sample. As I don't have the service code as you have so it is very simple to give it a test to check either it is working or not or it will give me the same error as like yours.
What I have done for testing this may be look trivial to you but please check , it works for me and give me right result. here is screen shot of Route Config file , take a look at the red circle ( I have to change this for web method works)
Screen shot of chrome dev tools ( for Contact.aspx page here for simplicity)
And finally Contact.aspx -> GetCompanies web method break point hit screen shot , here i have modified method body for simplicity , just to check data binding is working or not.
So , it's work for me. Would you please check all of your step one by one and let me know. If it will help you then it will be my pleasure.
I think you don't need to stringify it.
Instead of:
data: JSON.stringify({ CountryCode: selectedCountry, CompanyCode: 'SAU' }),
try:
data: { CountryCode: selectedCountry, CompanyCode: 'SAU' },
Very silly point I miss out here From web Method I Was returning CompanyCode as you can see
CountryCode = company.CompanyCode,
CompanyName = company.CompanyName
And In Html I was trying to bind CompanyId as you can see here :
$("#ddlCompany").append($("<option></option>").val(value.CompanyId).html(value.CompanyName));
So it was coming null or 0 for obvious region.
I Just replace value.CompanyId to CompanyCode and its now working perfectly
Do you need .aspx suffix?
Try like this url: "Header/GetCompanies",
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.
From razor view I'm sending js object using jquery to the mvc controller. Reason why I do it using jquery post method and not razors form is that I need to manage dynamic input of certain fields. On the view certain fields (inputtextbox) are dynamically added to the view (from 0 - 10) and I manage that solution using js on the page.
var myJsObj = ...
$.ajax({
type: 'POST',
traditional: true,
contentType: 'application/json',
url: '/MyController/SomeAction',
data: JSON.stringify({ model: myJsObj}),
success: function () {
}
});
On the server side, mvc receives that model and in case of some error I want to return this object back to the view.
[HttpPost]
public ActionResult SomeAction(MyModel model)
{
if(!ModelState.IsValid)
{
ModelState.AddModelError("", "Error occured!");
return View(model);
}
return RedirectToAction("Index");
}
I have inside razor view
Html.ValidationSummary
but since I'm using jquery post I dont know how to receive back to the view and display error like I would use regular razor form. Or if you know better approach to manage dynamically added input boxes on the razor view please post. Any help please.
I think you've got a couple of options here:
If you prefer to continue to use an Ajax POST as you've shown above, then you need to take the response from the POST and inject it back into your current HTML document. For example,
$.ajax({
type: 'POST',
traditional: true,
contentType: 'application/json',
url: '/MyController/SomeAction',
data: JSON.stringify({ model: myJsObj}),
success: function (data) {
// This is the case where the MVC action found model validation
// errors, and so it is responding with an HTML document that
// shows the errors.
var returnedBodyHtml = $(data).find('body').html();
$('body').html(returnedBodyHtml);
}
});
(That's untested code up there, so you may have to debug a little bit.) But this code doesn't handle the case where the server responded with a redirect (in the case of successful validation). So, check out this post for some options there.
Your other option is to use the standard Form submit. I know you said you had some dynamically generated input controls on your page, but that doesn't mean that you can't do a Form submit. You just need to make sure that these dynamically generated elements have the correct "name" attribute on them, so that their values get mapped appropriately to the Model on the server side action that is accepting the POST. For example, if your Javascript is dynamically generating an HTML element like this, and inserting it into the form:
<input type="text" name="myDynamicallyGeneratedInput[0]" />
<input type="text" name="myDynamicallyGeneratedInput[1]" />
<input type="text" name="myDynamicallyGeneratedInput[2]" />
<input type="text" name="myDynamicallyGeneratedInput[3]" />
then your Form submit will still work, as long as on the server side, your MyModel class has that corresponding property:
class MyModel
{
public List<string> MyDynamicallyGeneratedInput {get; set;}
}
This is what I have done to display errors for dynamic inputs. First off, take a look at this post to give you a better understanding. I have modified my code to better suit my needs, but you can check if it works for your application.
use-asp-net-mvc-validation-with-jquery-ajax.
I would then consume the return result in the ajax post error callback. It returns a code 400 'Bad Request' on validation errors. The validator variable is the form validator object.
error: function (xhr, textStatus, errorThrown) {
var statusCode = parseInt(xhr.status);
if (statusCode == 400) {
var data = $.parseJSON(xhr.responseText);
var message = "";
$.each(data, function (i, item) {
var propertyName = "" + item.key + "";
if ($("input[name='" + item.key + "']").length > 0) {
var errorObj = {};
errorObj[item.key] = item.error;
validator.showErrors(errorObj);
}
else {
message += "<div>" + item.key + ": " + item.error + "</div>";
}
});
if (message != "") {
//display message
}
}
}
I hope this helps. Good luck.
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.
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.