I've been following the online tutorials for my MVC project using Knockout and Entity Framework. I am also using a repository pattern.
From what I've been finding, the tutorials are returning strings when performing HTTP POST requests, as I have below. My concern is that the controller is returning strings - it just seems very rudimentary, and I can't seem to find a solid sample/tutorial of how I can do these POST requests otherwise (while not returning a view), as well as catching both database exceptions and POST exceptions as well.
Javascript:
self.saveNRI = function () {
var token = $('[name=__RequestVerificationToken]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
$.ajax({
type: "POST",
url: '/nris/Create',
headers: headers,
dataType: 'json',
data: ko.toJSON(self.nri),
contentType: 'application/json',
success: function (result) { },
error: function (err) {
if (err.responseText == "Success") {
window.location.href = '/nris/Index/';
}
if (err.responseText == "Failed") {
alert("save failed");
}
}
});
}
Controller:
[HttpPost]
public string Create(DTO incomingModel)
{
if (ModelState.IsValid){
try
{
_nriRepository.Insert(incomingModel);
}
catch (Exception ex)
{
return "Failed";
}
}
return "Success";
}
Repository:
public async void Insert(DTO n)
{
//Insert code removed for brevity
await _context.SaveChangesAsync();
}