How to know subcategory of category Dropdown Selection? - javascript

How can i Categorized in database uisng dropdownlist onces
I click INVORG category and show the available in DEPTCODE?
using Json
[HttpPost]
public JsonResult GetDEPTCODE(string id)
{
List<SelectListItem> states = new List<SelectListItem>();
///
//I got Error Code, can you please define my wrong code and correct thanks
states = from u in _db.USERGROUPs where u.INVORG == id
select(new SelectListItem {Text =u.INVORG, Value = u.DEPTCODE});
return Json(new SelectList(states, "Value", "Text"));
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#INVORG").change(function () {
$("#DEPTCODE").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetDEPTCODE")', // we are calling json method
dataType: 'json',
data: { id: $("#INVORG").val() },
// here we are get value of selected INVORG and passing same value
success: function (states) {
// states contains the JSON formatted list
// of states passed from the controller
$.each(states, function (i, state) {
$("#DEPTCODE").append('<option value="' + state.Value + '">' +
state.Text + '</option>');
// here we are adding option for States
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>

change your method to HttpGet as you are getting data.
[HttpGet]
public ActionResult GetDEPTCODE(string id)
{
List<SelectListItem> items= new List<SelectListItem>();
return Json(new { data = items}, JsonRequestBehavior.AllowGet);
}
change your script as below
$("#INVORG").change(function () {
$("#DEPTCODE").empty();
$.ajax({
type: 'GET',
url: '#Url.Action("GetDEPTCODE")', // we are calling json method
dataType: 'json',
data: { id: $("#INVORG").val() },
// here we are get value of selected INVORG and passing same value
success: function (data) {
// states contains the JSON formatted list
// of states passed from the controller
$("#DEPTCODE").html('');
$.each(data["data"], function (key, value) {
$("#DEPTCODE").append($("<option>
</option>").val(value.Value).html(value.Text));
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})

Related

Saving changes to the DB MVC

I have a problem when I try to save some data to the database. I can see the ID and Date returning me appropriate values in the JS function... However, the parameter for the Process function inside the controller class remains null. I don't know why is that happening. There is a linq query that is also included in the Hello Model, but I didn't include it because there is no need for it.
Model:
public class Hello
{
List<string> Ids { get; set; }
List<string> Dates { get; set; }
}
Controller:
[HttpPost]
public ActionResult Process(string ids, string dates)
{
Hello model = new Hello();
if (ModelState.IsValid)
{
using (db = new DB())
{
rp = new RequestProcess();
//var c = rp.getHello(model, dates);
var c = rp.getStuff();
if (c != null)
{
foreach (var i in c)
{
if (i != null)
{
ids = i.ID;
dates = i.Date.ToString();
}
db.SaveChanges();
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}
View:
<td><input class="id" type="checkbox" id=#item.ID /></td>
<td>#Html.DisplayFor(x => #item.ID)</td>
<td><input class="date" id=date#item.ID type="text" value='#item.Date'/></td>
$(document).ready(function () {
var ids = "";
var dates = "";
$("#btnSubmit").bind("click", function () {
createUpdateArrays();
var url = "/Sample/Process";
$.ajax({
type: "POST",
url: url,
data: { ids: ids, dates: dates },
contentType: 'application/json; charset=utf-8',
success: function (success) {
if (success === true) {
alert("HERE WE ARE");
}
else {
alert("eror");
}
}
});
ids = "";
dates = "";
});
function createUpdateArrays() {
var i = 0;
$('input.remedy-id:checkbox').each(function () {
if ($(this).is(':checked')) {
var rid = $(this).attr("id");
$('.planned-date').each(function () {
var did = $(this).attr("id");
if (did === rid) {
var date = $(this).val();
ids += rid + ",";
dates += date + ",";
}
});
};
});
};
Any help would be appreciated!
I think you need contentType: 'application/json' in your $.ajax({});
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json'
});
Also, try adding [FromBody]Hello model in your controller action.
There are several issues in your code:
1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.
2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.
Therefore, you should use AJAX setup as provided below:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#targetElement').html(result);
},
error: function (xhr, status, err) {
// error handling
}
});
Controller Action
[HttpPost]
public ActionResult Process(Hello model)
{
if (ModelState.IsValid)
{
using (db = new DB())
{
// save data
}
ViewBag.Message = "Success";
return PartialView("_PartialViewName", model);
}
else
{
ViewBag.Message = "Failed";
return PartialView("_PartialViewName", model);
}
}
Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).

What to do if Optional Parameter concept doesn't work?

I have a JS function which takes a value from a textbox based on the Radio button selected.
Example: If RadioButton No is Selected, values is teken from TextBox A, else if RadioButton Yes is selected, Value is taken from TextBox B. The following script is in my view
$('#btnVolunteerSaveBtn').on('click', function() { // on click of save button
if (document.getElementById('RadioNo').checked) { //ID of radio button NO
var checking = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
if (checking == "") {
//if nothing is entered, stop from saving in DB
} else {
x = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
$.ajax({
url: '#Url.Action("DonationValue","VolunteerInfo")',
data: {
name: x
},
type: "POST"
});
}
} else {
x = $('#GetNames').val(); //ID of textbox from where the value is to be taken if RadioButton Yes is selected
$.ajax({
url: '#Url.Action("DonationValue","VolunteerInfo")',
data: {
name: x
},
type: "POST"
});
}
});
Till here it seems to work fine. Now coming to the controller, I have a function DonationValue
My Question:
How can I pass the name parameter above?
If nothing is filled in TextBox with id #Donation, how do I stop
from saving the form in the DB?
My Attempt:
I tried doing
public string DonationValue(string name = null)
{
return name; //Trying to pass this value above
}
This didn't help. It resolved the error but the passed value was always null. I also tried a couple of other things but none helped.
Edited:
[HttpPost]
public ActionResult AddVolunteer(VolunteerInfo viewModel)
{
if (!ModelState.IsValid)
{
return View("AddVolunteer", viewModel);
}
var volunteer = new VolunteerInfo()
{
Name = viewModel.Name,
BirthdayDateTime = viewModel.BirthdayDateTime,
Address = viewModel.Address,
PhoneNumber = viewModel.PhoneNumber,
EmailAddress = viewModel.EmailAddress,
OccasionsID = viewModel.OccasionsID,
DonationForWhom = _DonationValue
};
if (!string.IsNullOrEmpty(volunteer.DonationForWhom))
{
_context.VolunteerInfos.Add(volunteer);
_context.SaveChanges();
return RedirectToAction("Index", "Home");
}
return //something to save state so that user doesnt have to enter all the values again
}
[HttpPost]
public void DonationValue(string name)
{
_DonationValue = name;
}
#Daisy Shipton.
Is this a better solution?
<script>
$(function() {
$('#btnVolunteerSaveBtn').on('click', function() { // on click of save button
debugger;
if (document.getElementById('RadioNo').checked) { //ID of radio button NO
var checking = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
if (checking == "") {
//if nothing is entered, stop from saving in DB
}
else {
var x = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
var jsonObject = {
"textValue": x,
"isRadioSelected": "true" // show the radio is selected
};
$.ajax({
url: '#Url.Action("AddVolunteer", "VolunteerInfo")',
data: JSON.stringify(jsonObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
}
}
else {
var jsonObject2 = {
"textValue": $('#GetNames').val(),
"isRadioSelected": "false" // show the radio is not selected
};
$.ajax({
url: '#Url.Action("AddVolunteer", "VolunteerInfo")',
data: JSON.stringify(jsonObject2),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
}
});
})
</script>
In my controller:
[HttpPost]
public ActionResult AddVolunteer(VolunteerInfo volunteerInfo)
{
if (volunteerInfo.isRadioSelected)
{
//something
}
else
{
//something
return View();
}
1) Client calls to DonationValue post method with name paramter
e.g. name="abc"
[HttpPost]
public string DonationValue(string name = null) // name = "abc"
{
return name; //Trying to pass this value above
}
This returned value to be stored in client side say variable retunedDonationValue
If you don't pass any name parameter then above post method does return empty string then just set retunedDonationValue = ''
2) Now you have to pass above retunedDonationValue to your post method in posted json object like
var jsonObject =
{
"Name" = "YourName",
"BirthdayDateTime" = "YourBirthdayDateTime",
"Address" = "YourAddress",
"PhoneNumber" = "YourPhoneNumber",
"EmailAddress" = "YourEmailAddress",
"OccasionsID" = "YourOccasionsID",
"DonationForWhom" = retunedDonationValue //Note here
}
3) And pass this post data to http call to AddVolunteer
$.ajax({
url: '#Url.Action("AddVolunteer", "VolunteerInfo")',
data: JSON.stringify(jsonObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
4) And your action method is look like
[HttpPost]
public ActionResult AddVolunteer(VolunteerInfo viewModel)
{
if (!ModelState.IsValid)
{
return View("AddVolunteer", viewModel);
}
var volunteer = new VolunteerInfo()
{
Name = viewModel.Name,
BirthdayDateTime = viewModel.BirthdayDateTime,
Address = viewModel.Address,
PhoneNumber = viewModel.PhoneNumber,
EmailAddress = viewModel.EmailAddress,
OccasionsID = viewModel.OccasionsID,
DonationForWhom = viewModel.DonationForWhom
};
if (!string.IsNullOrEmpty(volunteer.DonationForWhom))
{
_context.VolunteerInfos.Add(volunteer);
_context.SaveChanges();
}
return View(viewModel);
}

Pass table input to controller

I'm new to programming and I want to pass a table input value to the controller. I tried this:
$("#btnsend").click(function () {
$.ajax({
type: "POST",
contentType: "application/json ; charset=utf-8",
data: {
buyerID: $('.BuyerID').val(),
},
url: "/SaveReservation",
success: function (data) {
alert('buyerID : ' + data);
},
error: function (result) {
alert('something went wrong');
}
})
});
The controller is like this :
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult SaveReservation(BuyerModel buyer)
{
return Json(buyer.DistibutorID);
}
When I click the button I get a success state but in the alert I get all the source code of the project after the word buyerID.
You may want to try this:
return Json(new { success = true, message = buyer.DistibutorID },
JsonRequestBehavior.AllowGet);
And:
alert('buyerID : ' + data.message );
Notice that this here in your script
data: {
buyerID: $('.BuyerID').val(),
},
Either must have the same structure as your BuyerModel Here
public JsonResult SaveReservation(BuyerModel buyer) <- BuyerModel that you are using
{
return Json(buyer.DistibutorID);
}
Or you can Just Change your Controller to accept only one argument Like this
public JsonResult SaveReservation(string buyerID) <- Follow the same Object structure you are passing in Ajax
{
return Json(buyer.DistibutorID);
}

Passing data from JavaScript to MVC Controller

Wellcome!
I have a problem with passing data from JavaScript to MVC Controller. Im new to MVC so I probably miss something.
$("#example").keypress(function (event) {
var data = "example";
$.ajax({
url: "/example/example",
type: "POST",
dataType: "json",
data: { example: data },
success: function (example) {
var items = "";
$.each(data, function (i, example) {
items += "<option>" + example + "</option>";
});
$("#example").html(items);
}
});
});
public class PeoplePickerController : BaseController
{
// GET: PeoplePicker
public ActionResult PeoplePicker(object data)
{
if (HttpContext.Request.IsAjaxRequest())
{
IQueryable logins = (IQueryable)QueryDatabaseForUsersAndGroups((string)data, Context.Users);
return Json(new SelectList(example, "example"), JsonRequestBehavior.AllowGet);
}
return PartialView();
}
}
data parameter is always null.

Pass json/javascript data/objects to c# function using ajax

I'm using FullCalendar (http://arshaw.com/fullcalendar/) and I need help with passing data using json to a c# function in the code behind page of my ASP.net page.
I am using json to load data like so in my FullCalendar web application:
Code behind:
[WebMethod]
public static List<Event> GetEvents()
{
List<Event> events = new List<Event>();
events.Add(new Event()
{
EventID = 1,
EventName = "EventName 1",
StartDate = DateTime.Now.ToString("MM-dd-yyyy"),
EndDate = DateTime.Now.AddDays(2).ToString("MM-dd-yyyy"),
EventColor = "red"
});
events.Add(new Event()
{
EventID = 2,
EventName = "EventName 2",
StartDate = DateTime.Now.AddDays(4).ToString("MM-dd-yyyy"),
EndDate = DateTime.Now.AddDays(5).ToString("MM-dd-yyyy"),
EventColor = "green"
});
return events;
}
asp.x page:
events: function(start, end, callback)
{
$.ajax(
{
type: 'POST',
contentType: 'application/json',
data: "{}",
dataType: 'json',
url: "Calendar.aspx/GetEvents",
cache: false,
success: function (response) {
var events = $.map(response.d, function (item, i) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.end = new Date(item.EndDate);
event.title = item.EventName;
event.color = item.EventColor;
return event;
})
callback(events);
},
error: function (err) {
alert('Error');
}
});
},
This is working fine. Now I want to save data by calling a function and passing it data. Here is what I have done so far:
Code behind:
[WebMethod]
public static bool SaveEvents(List<Event> events)
{
//iterate through the events and save to database
return true;
}
asp.x page
function save() {
var eventsFromCalendar = $('#calendar').fullCalendar('clientEvents');
var events = $.map(eventsFromCalendar, function (item, i) {
var event = new Object();
event.id = item.id;
event.start = item.start;
event.end = item.end;
event.title = item.title;
event.color = item.color;
return event;
});
$.ajax(
{
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(events), **<-- I have to pass data here but how???**
dataType: 'json',
url: "Calendar.aspx/SaveEvents",
cache: false,
success: function (response) {
alert('Events saved successfully');
},
error: function (err) {
alert('Error Saving Events');
}
});
return false;
}
The above ajax post is where I need help with. The variable events contais all the FullCalendar event info.
How do I pass the data 'events' to the function 'SaveEvents'?
I can change the SaveEvents signature if need be.
EDIT
If I change my c# function to use an array like s0:
[WebMethod]
public static bool SaveEvents(Event[] newEvents)
{
return true;
}
And pass the following data through:
data: JSON.stringify({ newEvents: events }),
Then the function 'SaveEvents' gets called with an array of size 4 but all the data values are null, why is this?
Thanks
Obvious from your code that you have a c# class as
public class Events
{
public int EventID {get; set;}
public string EventName {get;set;}
public StartDate {get; set;}
public string end {get; set;}
public string color {get; set;}
}
So take json array. A sample here
// Array which would be provided to c# method as data
var newEvents=[
{
EventID : 1,
EventName : "EventName 1",
StartDate : "2015-01-01",
EndDate : "2015-01-03",
EventColor : "red"
},
{
EventID : 2,
EventName : "EventName 2",
StartDate : "2015-01-02",
EndDate : "2015-01-04",
EventColor : "green"
}
];
Now the ajax request which passes JSON objects to posted URL
$.ajax
({
type: 'POST',
contentType: 'json',
data: {newEvents:newEvents},// Pass data as it is. Do not stringyfy
dataType: 'json',
url: "Calendar.aspx/SaveEvents"
success: function (response) {
alert('Events saved successfully');
},
error: function (err) {
alert('Error Saving Events');
}
});
Update :
To make sure that there is nothing else wrong please test your Save Events as. If it goes fine above should work as well, As it is working for me :)
[WebMethod]
public static bool SaveEvents(string EventName)
{
//iterate through the events and save to database
return true;
}
$.ajax
({
type: 'POST',
contentType: 'json',
data: {EventName:'myevet 1'},
url: "Calendar.aspx/SaveEvents",
cache: false,
success: function (response) {
alert('Events saved successfully');
},
error: function (err) {
alert('Error Saving Events');
}
});

Categories