Passing Multiple parameters to Web Method using jQuery in ASP.NET C# - c#

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",

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>
}

Kendo TreeView Sync method on datasource not working

I have Kendo TreeView in which I can Call an Ajax method and hit my MVC controller method
However, my understanding was that
update: "should" be called with datasource.sync() ( homogeneous = my datasource )
$("#syncCall").click(function(e) {
console.log('before sync');
homogeneous.sync();
});
This DOES show before sync in chrome dev console ....
However, my mvc controller method SyncAllNodes breakpoint is NEVER hit.
Here is the HierarchicalDataSource
var homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot + "/GetReportGroupAssignments",
dataType: "json"
},
update: {
url: "/Report/SyncAllNodes",
dataType: "json"
}
},
schema: {
model: {
id: "Id" //"ReportGroupName"
,
hasChildren: "Id"
}
}
});
Joseph,
Not sure if this has anything to do with it, but your Update url looks different than your Read url. Namely, the "serviceRoot +" part. Can you verify that the Update url points to the correct location?
Are you getting any javascript errors after the console.log(...) call?
Also, confirm that you have changes to save. If there are no changes, the sync method will not do anything.
Regards,

manage serverside validaton when I use jquery post

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.

mvc form collection issue

I am facing a weird problem. I have a cshtml form:
<label class="pre_req_questions_width">
#Html.RadioButton("radioGroup" + Model.ID, "1", (Model.ExpectedResponse == 1 ? true : false), new { id = "rbtnYes", style = "margin-top:0px; margin-right:10px;" })Yes</label>
<label class="pre_req_questions_width">
#Html.RadioButton("radioGroup" + Model.ID, "2", !(Model.ExpectedResponse == 1 ? true : false), new { id = "rbtnNo", style = "margin-top:0px;margin-right:10px;" })No</label>
On form submit, I am getting radio group value like this:
int radioValue = int.Parse(fc.GetValue(controlID).AttemptedValue);
It works fine when i call it from #Html.BeginForm(), but when i try to send form collection via ajax like this:
input = $(':input')
$.ajax({
type: "POST",
url: '#Url.Action("SavePrerequisiteQuestion", "Dashboard", new { id = #Model.ID })',
data: input,
dataType: "html",
success: function (msg) {
alert("fine");
}, error: function (req, status, error) {
// with error
alert(error);
}
});
It send both values like this "1,2" rather than sending just selected/submitted value.
In your ajax request, you're sending all :input elements as your data:
...
data: input
...
What you probably want is to just serialize your form data, and send it with the request:
...
data: input.closest('form').serialize()
...
This is assuming you have your radio buttons in a <form> tag.
It may not be so easy to work around this. For instance, to get a selected radio button, you can do this: jQuery get value of selected radio button
So you can't just take all inputs and get the values from them... instead, you have to have more of a selective approach, and handle different elements appropriately. Checkboxes and selects will also have a similar problem.
You can put the #Html.Beginform back in and hijack the form submit in your jQuery
$('#formID').on('submit', function(e){
e.preventDefault(); // Just to stop the automatic Non Ajax submission of the form
$.post($(this).attr('action'), $(this).serialize(), function (data) {
//do stuff on success callback
alert("fine");
});
});
You can inherit the action path from the Html.BeginForm itself in the path below by doing
$(this).attr('action')
Note: If you want to manually put the path in there you still can instead of getting it
from the form
Then use $(this).serialize() to just serialize the whole form like the person above me
suggested

MVC and JQuery: Best practice for retrieving form data

I have some JQuery that uses Ajax to send information back to my controller to be processed
I am doing it like this:
//Define my controls
<%=Html.TextBox("PName", Model.PName, new { id = "pName" })%> ...
....
....
//Get the values from my controls
var param1= $("#pName").val();
....
....
//Define the return URL. Is this how to send info back?
var url = '<%= Url.Content("~/Port/SaveRowAjax") %>/?ID=' + id
+ "&param1=" + param1
+ "&param2=" + param2
+ "&param3=" + param3
+ "&param4=" + param4
+ "&param5=" + param5;
$.ajax({
url: url,
success: function(html) {
alert("Success!");
},
});
//My c# code, that processes the request
public void SaveRowAjax(string param1 ....)
{
...
}
Is this the best way of doing it with MVC?
It seems a bit messy when i am contructing the URL to post back to the server
Try using SerializeArray for submitting your form items. It'll box all their values into a JSON object.
var link = "/Port/SaveRowAjax";
var formData = $(":input").serializeArray();
$.post(link,formData);
You can try to use such syntax with jQuery
$.post(link, {param1: param1, param2: param2 });
The way that works for me is this:
jQuery.ajax({
url: '#Url.Action("SaveRowAjax", "Port")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ param1: param1, param2: param2, param3: param3 }),
success: function (result) { }
});
Theres a few ways to do this. I prefer the method outlined here:
http://weblogs.asp.net/mikebosch/archive/2008/02/15/asp-net-mvc-submitting-ajax-form-with-jquery.aspx
Yes, it is based on an older version of MVC but the real beef of the technique is the use of jQuery (which hasnt changed).
One limitation of the technique is that it wont work with file uploads, however, there is a jQuery plugin for doing ajax form posts that does support file uploads (I think through a hidden iframe).
edit:
I think the best reason to use this technique is that if the user has javascript disabled, the form will still work.

Categories