Why it was not rendering events in full-calendar from WEB SERVICE? - c#

//My web-service method WebService1.asmx
[WebMethod]
[ScriptMethod]
public string GetAllEvents()
{
var list = new List<string>();
list.Add("[{\"id\":\"36\"title\":\"Birthday party\",\"start\":\"2013-09-18\",\"end\":\"2013-09-18\",\"allDay\":false}]");
JavaScriptSerializer jss = new JavaScriptSerializer();
string strJSON = jss.Serialize(list.ToArray());
return strJSON;
}
//My jQuery snippet
$("#fullcalendar").fullCalendar({
eventSources:
[
{
url: "http://localhost:49322/WebService1.asmx/GetAllEvents",
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
}
]
});

You are on the wrong track.
Don't form your json strings manually using string operations (As in your case, it is an invalid json).
Don't return string from your web method, return the real object
It should be something like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Event> GetAllEvents()
{
List<Event> events = .......
..fill the list....
return evetns;
}
public class Event
{
public int id { get; set; }
public string title { get; set; }
public string start { get; set; }
public string end { get; set; }
public bool allDay { get; set; }
}

Related

How to get each value from table in ASP.NET MVC?

I get each value but it doesn't display on DSChiTiet. How can I fix it? It only gets value TenKH, NgayLap, TongTien.
DSChiTiet doesn't get value from table and displays null. enter image description here
Thank you very much for your help <3.
My model PhieuBanHangModel
public class PhieuBanHangViewModel
{
public int MaPBH { get; set; }
public string TenKH { get; set; }
public DateTime NgayLap { get; set; }
public decimal TongTien { get; set; }
public IEnumerable<CT_PhieuBanHangViewModel> DSChiTiet { get; set; }
}
My model CT_PhieuBanHangModel
public class CT_PhieuBanHangViewModel
{
public int MaPBH { get; set; }
public int MaSP { get; set; }
public int SoLuong { get; set; }
public decimal DonGia { get; set; }
public decimal ThanhTien { get; set; }
}
Controller Create Json
[HttpPost]
public JsonResult Create(PhieuBanHangViewModel phieuBanHang)
{
return Json(data: "", JsonRequestBehavior.AllowGet);
}
Function in View
function ThanhToan() {
var phieuBanHang = {};
var dsct_PhieuBanHang = new Array();
phieuBanHang.TenKH = $("#txtTenKH").val();
phieuBanHang.NgayLap = $("#txtNgayGiaoDich").val();
phieuBanHang.TongTien = $("#txtTongTien").val();
$("table tr:not(:first)").each(function () {
var ct_PhieuBanHang = {};
ct_PhieuBanHang.MaSP = parseFloat($(this).find("td:eq(0))").text());
ct_PhieuBanHang.SoLuong = parseFloat($(this).find("td:eq(4))").text());
ct_PhieuBanHang.DonGia = parseFloat($(this).find("td:eq(6))").text());
ct_PhieuBanHang.ThanhTien = parseFloat($(this).find("td:eq(7))").text());
dsct_PhieuBanHang.push(ct_PhieuBanHang);
});
phieuBanHang.DSChiTiet = dsct_PhieuBanHang;
$.ajax({
async: true,
type: 'POST',
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(phieuBanHang),
url: '/Manager/CT_PhieuBanHang/Create',
success: function (data) {
},
error: function () {
alert('Lỗi');
}
});
}
You may need to inherit ApiControllerand add the [FromBody] attribute to the binding model:
public class MyController : ApiController
{
/* something else... */
// /Manager/CT_PhieuBanHang/Create
[HttpPost]
public JsonResult Create([FromBody] PhieuBanHangViewModel phieuBanHang)
{
return Json(data: "", JsonRequestBehavior.AllowGet);
}
/* something else... */
}
For your jQuery code, make sure thet:$("table tr:not(:first)") do returns an array contains at least 1 item. (You can verify that by doing a console.log(phieuBanHang) to print out your data).

How to Send json object with fromdata to mvc controller

I am sending formdata data object to mvc controller. I received the array in controller but the object is always missing. Searched a lot about it did not find a clue.
I have tried to send whole object or appending each value to formdata but its always null. does formdata accepts? nested object.
My jQuery code:
function addstudent() {
var form= $("#studentform").valid();
if (form)
{
personfood.details.firstname = $("#firstname").val();
personfood.details.lastname = $("#lastname").val();
personfood.details.imageuploaded = $("#imageupload")[0].files[0];
personfood.details.rememberme = $("#rememberme").is(":checked");
personfood.details.newsletter = $("#newsletter").is(":checked");
personfood.details.gender = $("input[name='gender']").val();
var personfoods = new FormData();
$.each(personfood.details, function (key, value) {
personfoods.append(key, value);
});
$.each(personfood.foodname, function (key, value) {
personfoods.append("foodname["+[key]+"]", value);
});
for (var pair of personfoods.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
$.ajax({
url: "/Main/addperson",
type: "POST",
processData: false,
cache: false,
contentType: false,
dataType: "json",
data: personfoods,
success: onsucessinsert,
error:onerrorinsert
})
}
My ViewModel
public class personfoods
{
public details details { get; set; }
public List<string> foodname { get; set; }
}
details model:
public class details
{
public int id { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
public string imagename { get; set; }
public string imageshorturl { get; set; }
public string imagefullurl { get; set; }
public bool rememberme {get;set;}
public bool newsletter { get; set; }
public string gender { get; set;}
public HttpPostedFileBase imageuploaded { get; set; }
}
i solve it using $.each and appending key value pairs to my formdata.
$.each(personfood.details, function (key, value) {
personfoods.append("details[" + key + "]",value);
});
ContentType should be ''application/json; charset=utf-8" and you can not post files like you are doing. I think data:JSON.stringify(personfoods); should work for remaining properties.

Send Model With Json In Asp.net Core

I want to pass the model from controller to Success method in View and access the properties from the model with json. How do I write and how to access the properties in Success method?
public async Task<IActionResult> Edit( Department department)
{
if (ModelState.IsValid)
{
_genericRepository.Update(department);
await _genericRepository.SaveChangesAsync();
var model = _genericRepository.GetByIdAsync(department.Department_Id);
return Json(new { Message = model });
}
return Json(department);
}
<script>
function Success(data)
{
alert(data.Messge);
}
function Failure() {
}
</script>
How about:
$.ajax({
url: "<path>/Edit",
type: "POST",
data: JSON.stringify(department),
dataType: "json",
cache: false,
success: function (data) {
[...]
},
error: function () {
[...]
}
})
You can access data list from json file when using Json.Parse();
<script>
function Success(data)
{
var getDataList = Json.parse(data);
alert(getDataList);
}
function Failure() {
}
</script>
public ActionResult Import()
{
string response = JsonConvert.SerializeObject(responseModel);
return this.Content(response);
}
class ResponseModel
{
public string bodyone { get; set; }
public string bodytwo { get; set; }
public string HeadersFile1 { get; set; }
public string HeadersFile2 { get; set; }
public string FileName1 { get; set; }
public string FileName2 { get; set; }
}
then parse the response using JSON parser. Now you can read property values from ajax success like this
success: function (response) {
if (response.length == 0)
alert('Some error occured while uploading');
else {
var obj = JSON.parse(response);
$('#divPrint').html(obj.bodyone);
$('#divPrint2').html(obj.bodytwo);
$('#fileName1').html(obj.FileName1);
$('#fileName2').html(obj.FileName2);
$('#headersFile1').html(obj.HeadersFile1);
$('#headersFile2').html(obj.HeadersFile2);
}
}

Posting FormData from Angular to Web API, data always null

I'm posting some formData from my Angular 5 app to my Web API. Here's the typescript code:
public postFormData() {
const form = $('#customListForm')[0];
const formData = new FormData();
formData.append('tenant', form[0].value);
formData.append('username', form[1].value);
formData.append('password', form[2].value);
formData.append('CL_title', form[3].value);
formData.append('CL_description', form[4].value);
formData.append('CL_contentType', form[5].value);
formData.append('CL_template', form[6].value);
// const json = JSON.stringify(formData);
this.http.post(this.apiURL, formData, this.httpOptions).catch(this.errorHandler).subscribe(res => this.formPosted(res));
// this.http.get(this.apiURL).catch(this.errorHandler).subscribe(res => this.formPosted(res));
}
Here's my httpOptions:
private httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
})
};
I've tried various content types like application/json, or multipart/form-data but none work too.
Here's my Controller Post Action:
// POST api/customlist
[HttpPost]
public System.Web.Http.IHttpActionResult Post(CustomList data)
{
var test = HttpContext.Current.Request;
var testje = data;
return Ok("POST all good");
}
Here you can see my CustomList custom object:
public class CustomList
{
public CustomList()
{
}
public string Tenant { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string CL_title { get; set; }
public string CL_description { get; set; }
public string CL_contentType { get; set; }
public string CL_template { get; set; }
}
As you can see it contains the same fields as my formData & has a default/empty constructor.
No matter what I try, I always get my "data" to be null... Any ideas?

Object not received in Backend POST method as sent through $.ajax

The problem is that I am sending an object array in correct format through $4.ajax to a POST method in MVC, but on the backend it is not receiving as expected. If I send an Array of 3 objects, it shows that the backend object is received as a List of 3 objects, but the attributes in those objects are not loaded properly. Infact, none of the values are copied.
Here is the relevant javascript code
var array = new Array();
for (var i = 0 ; i < $('.TourCommission:enabled').length; i++)
{
var data = {
TourCodeID: parseInt($('.TourCommission:enabled').eq(i).parent().prev().html()),
Commission: parseFloat($('.TourCommission:enabled').eq(i).val())
};
array.push(data);
}
$.ajax({
url: '/Booking/submitAgentTourCommissions',
data: JSON.stringify(array),
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('form').submit();
},
error: function () {
return true;
}
});
Here is the backend code
[HttpPost]
public JsonResult submitAgentTourCommissions(List<AgentTourCommission> obj) {
return Json(true);
}
The AgentTourCommission class is as below
public class AgentTourCommission
{
public int UserID;
public string UserName;
public int TourCodeID;
public string TourCodeName;
public float Commission;
}
screenshot of Javascript Watch
screenshot of BackEnd Watch
You need add the get set like this:
public class AgentTourCommission
{
public int UserID { get; set; }
public string UserName { get; set; }
public int TourCodeID { get; set; }
public string TourCodeName { get; set; }
public float Commission { get; set; }
}
I hope you help!

Categories

Resources