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).
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?
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!
This is my c# code:
public void addBoxScore(string[] playerstats)
{
Games gamestats = new Games();
gamestats.GAME_ID = Int32.Parse(playerstats[0]);
gamestats.TEAM_ID = Int32.Parse(playerstats[1]);
gamestats.TEAM_ABBREVIATION = playerstats[2];
gamestats.TEAM_CITY = playerstats[3];
gamestats.PLAYER_ID = Int32.Parse(playerstats[4]);
gamestats.PLAYER_NAME = playerstats[5];
gamestats.START_POSITION = playerstats[6];
gamestats.COMMENT = playerstats[7];
gamestats.MIN = Int32.Parse(playerstats[8]);
gamestats.FGM = Int32.Parse(playerstats[9]);
gamestats.FGA = Int32.Parse(playerstats[10]);
gamestats.FG_PCT = Int32.Parse(playerstats[11]);
gamestats.FGTHREEM = Int32.Parse(playerstats[12]);
gamestats.FGTHREEA = Int32.Parse(playerstats[13]);
gamestats.FGTHREE_PCT = Int32.Parse(playerstats[14]);
gamestats.FTM = Int32.Parse(playerstats[15]);
gamestats.FTA = Int32.Parse(playerstats[16]);
gamestats.FT_PCT = Int32.Parse(playerstats[17]);
gamestats.OREB = Int32.Parse(playerstats[18]);
gamestats.DREB = Int32.Parse(playerstats[19]);
gamestats.REB = Int32.Parse(playerstats[20]);
gamestats.AST = Int32.Parse(playerstats[21]);
gamestats.STL = Int32.Parse(playerstats[22]);
gamestats.BLK = Int32.Parse(playerstats[23]);
gamestats.TO = Int32.Parse(playerstats[24]);
gamestats.PF = Int32.Parse(playerstats[25]);
gamestats.PTS = Int32.Parse(playerstats[26]);
gamestats.PLUS_MINUS = Int32.Parse(playerstats[27]);
}
and this is my javascript that gets the data from the api and sends it to the controller.
var date = "05/05/2014";
$.ajax({
dataType: "jsonp",
type: "post",
crossDomain: true,
url: 'http://stats.nba.com/stats/scoreboard/?LeagueID=00&gameDate=' + date + '&DayOffset=0',
success: function (val) {
var result = val.resultSets[0].rowSet;
$.each(result, function (key, value) {
var gameID = this[2];
$.ajax({
dataType: "jsonp",
async: false,
type: "post",
crossDomain: true,
gameID: { gameID: gameID },
url: "http://stats.nba.com/stats/boxscore?GameID=" + gameID + "&RangeType=0&StartPeriod=0&EndPeriod=0&StartRange=0&EndRange=0",
success: function (gameinfo) {
var w = gameinfo.resultSets[0].rowSet[0];
if (w[4] == "Final") {
var pstats = gameinfo.resultSets[4].rowSet;
$.each(pstats, function (key, value) {
var playerstats = this;
$.ajax({
async: false,
type: "post",
url: "/Stats/addBoxScore",
data: { playerstats: JSON.stringify(playerstats) },
done: function (data) {
console.log(data);
},
error: function (jqXHR, err) {
console.log(err);
}
});
});
};
}
And this is what the data that the controller recieves looks like:
"[\"0041300201\",1610612764,\"WAS\",\"Washington\",2772,\"Trevor Ariza\",\"F\",\"\",\"37:20\",7,10,0.7,6,6,1,2,4,0.5,1,5,6,2,1,0,0,3,22,18]"
This is my model:
public class Games
{
[Key, Column(Order = 0)]
public int GAME_ID { get; set; }
public int TEAM_ID { get; set; }
public string TEAM_ABBREVIATION { get; set; }
public string TEAM_CITY { get; set; }
[Key, Column(Order = 1)]
public int PLAYER_ID { get; set; }
public string PLAYER_NAME { get; set; }
public string START_POSITION { get; set; }
public string COMMENT { get; set; }
public int MIN { get; set; }
public int FGM { get; set; }
public int FGA { get; set; }
public int FG_PCT { get; set; }
public int FGTHREEM { get; set; }
public int FGTHREEA { get; set; }
public int FGTHREE_PCT { get; set; }
public int FTM { get; set; }
public int FTA { get; set; }
public int FT_PCT { get; set; }
public int OREB { get; set; }
public int DREB { get; set; }
public int REB { get; set; }
public int AST { get; set; }
public int STL { get; set; }
public int BLK { get; set; }
public int TO { get; set; }
public int PF { get; set; }
public int PTS { get; set; }
public int PLUS_MINUS { get; set; }
public virtual Player player { get; set; }
}
Why does it put \ in every string in the array? And how do i parse it to my model?
I think this should help.
using System.Web.Helpers;
public void addBoxScore(string playerstats)
{
Games gamestats = Json.Decode<Games>(playerstats);
}
Edits
Well, I'm not sure that fully understand the structure of your model, but... Try the following:
public void addBoxScore(string playerstats)
{
var gamestats = System.Web.Helpers.Json.Decode<IEnumerable<Games>>(playerstats);
}
More Edits
Now I can spot the problem. Json.Decode() will not help you to create your Games object because data you send to controller is just stringnified array of strings and property names, which are required for converting are not provided. Maximum what you can do - deserialize this string to proper C# string array manually, and then do what you have already done - assign each property one by one. You can refactor it to look more pretty, create some extension method for string or even use reflection to loop through Games properties for assignment ... For example:
public static class Extensions
{
public static Games ToGames(this string data)
{
var playerstats = data
.Replace("[", string.Empty)
.Replace("]", string.Empty)
.Replace(#"\", string.Empty)
.Replace("\"", string.Empty)
.Split(',')
.Select(s => s.Trim())
.ToArray();
var gamestats = new Games
{
GAME_ID = Int32.Parse(playerstats[0]),
TEAM_ID = Int32.Parse(playerstats[1]),
TEAM_ABBREVIATION = playerstats[2],
TEAM_CITY = playerstats[3],
PLAYER_ID = Int32.Parse(playerstats[4]),
PLAYER_NAME = playerstats[5],
START_POSITION = playerstats[6],
COMMENT = playerstats[7],
MIN = Int32.Parse(playerstats[8]),
FGM = Int32.Parse(playerstats[9]),
FGA = Int32.Parse(playerstats[10]),
FG_PCT = Int32.Parse(playerstats[11]),
FGTHREEM = Int32.Parse(playerstats[12]),
FGTHREEA = Int32.Parse(playerstats[13]),
FGTHREE_PCT = Int32.Parse(playerstats[14]),
FTM = Int32.Parse(playerstats[15]),
FTA = Int32.Parse(playerstats[16]),
FT_PCT = Int32.Parse(playerstats[17]),
OREB = Int32.Parse(playerstats[18]),
DREB = Int32.Parse(playerstats[19]),
REB = Int32.Parse(playerstats[20]),
AST = Int32.Parse(playerstats[21]),
STL = Int32.Parse(playerstats[22]),
BLK = Int32.Parse(playerstats[23]),
TO = Int32.Parse(playerstats[24]),
PF = Int32.Parse(playerstats[25]),
PTS = Int32.Parse(playerstats[26]),
PLUS_MINUS = Int32.Parse(playerstats[27])
};
return gamestats;
}
}
And then in your controller:
public void addBoxScore(string playerstats)
{
Games result = playerstats.ToGames();
}
Also I have a question - What is MIN = Int32.Parse(playerstats[8])? Because it has a value of 37:20 (in example string you provided) and I'm not sure I understand what is this, because it will give the error during conversion to int.
//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; }
}