Im trying to learn some MVC, therefore I created a webpage with a master/detail saving form. My problem is: I get this error message:
SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request. (XHR): POST
when I add foreach()
in the controller action to save the details.
Without foreach()
its working fine.
Im using a database first approach.
These are my tables:
CREATE TABLE [dbo].[TicketMaster] (
[TicketID] INT IDENTITY (1, 1) NOT NULL,
[Titel] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([TicketID] ASC)
);
and
CREATE TABLE [dbo].[TicketDetails] (
[TicketDetailsId] INT IDENTITY (1, 1) NOT NULL,
[TicketID] INT NOT NULL,
[ItemName] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([TicketDetailsId] ASC),
CONSTRAINT [FK_TicketDetails_TicketMaster] FOREIGN KEY ([TicketID])REFERENCES [dbo].[TicketMaster] ([TicketID])
);
My ViewModel:
public class TLSModel
{
public string Titel { get; set; }
public List<TicketDetail> TicketDetails { get; set; }
}
Jquery:
$(document).ready(function () {
var list = [];
$('#add').click(function () {
list.push({
ItemName: $('#ItemName).val().trim()
});
$('#ItemName).val('').focus();
GeneratedItemsTable();
});
$('#submit').click(function () {
var data = {
Titel: $('#Titel').val().trim(),
TicketDetails: list
}
$.ajax({
url: '/Ticket/Create',
type: "POST",
data: JSON.stringify( data ),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
if (d.status == true) {
alert('Successfully done.');
list = [];
$('#Titel').val('');
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
error: function () {
alert('Error. Please try again.');
$('#submit').val('Save');
}
});
});
function GeneratedItemsTable() {
...some Code...
}
});
Controller Action:
public JsonResult Create (TLSModel T)
{
bool status = true;
TicketMaster ticket = new TicketMaster { Titel = T.Titel };
foreach(var i in T.TicketDetails)
{
ticket.TicketDetails.Add(i);
}
db.TicketMasters.Add(ticket);
db.SaveChanges();
return new JsonResult { Data = new { status = status } };
}
Well I just fixed my problem. Therefore I deleted and recreated the ADO.Net Entity Data Model. Seems that I somehow messed things up in there.
Still many thanks to mateudu for your help, really appreciated that.