Ajax populating dropdown for c# results in undefined - c#

I only get the text message Selektoni Tipin, but I dont get any values from the tables I only get undefined
AJAX script
script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Dokument/Dokument",
data: "{}",
success: function (data) {
var s = '<option value="-1">Selektoni Tipin</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].Id_Tipi + '">' + data[i].Emri_llojit + '</option>';
}
$("#tipiDropdown").html(s);
}
});
});
</script>
Controller method
public ActionResult Dokument()
{
return View();
}
// GET: NgarkoDokument
public ActionResult GetTipi(int tipiId)
{
Test_kristiEntities db = new Test_kristiEntities();
return Json(db.Tipi.Select(x => new
{
Id_Tipi = x.Id_Tipi,
Emri_llojit = x.Emri_llojit
}).ToList(), JsonRequestBehavior.AllowGet);
// return View();
}
Model i built with some tables
public class NgarkoDokument
{
public Dokumenti Dokumenti { get; set; }
public Fusha_Indeksimit FushaIndeksimit { get; set; }
public Vendndodhja_Fizike Vendndodhja_fizike { get; set; }
public Tipi Tipi { get; set; }
}
And here is the html
<select title="Lloji i dokumentit" name="lloji" class="form-control col-md-3 box" id="tipiDropdown"> </select>

Related

.NET Core Ajax still redicted me to json response page

I try to insert data to database with .NET Core Framework with AJAX hope this can return json response when it success, it success but i don't know it throws me to page fill it the response of json, not still in page when i insert the data. (sorry for link image, i'm not yet proper to upload image, stackoverflow say)
This is output i get;
https://i.stack.imgur.com/x7UY4.png
This is create in contoller;
https://i.stack.imgur.com/0StbY.png
This is my javascript code;
var isDuplicate = true;
$("#formProduct").validate({
rules: {
NameProduct: {
required: true,
minlength: 5
}
},
messages: {
NameProduct: {
required: "Data tidak boleh kosong",
minlength: "Minimal 5 huruf"
}
},
submitHandler:function(form){
debugger;
if (isDuplicate) {
return false;
} else {
submitAJAX(form);
}
debugger;
}
});
function submitAJAX(form) {
var fromData = new FormData();
var dataForm = $(form).serializeArray();
$.each(dataForm, function (key, input) {
fromData.append(input.name, input.value);
});
var file = $("#ImageFile").prop("files");
if (file.length > 0) {
fromData.append("ImageFile", file[0]);
}
$.ajax({
url: "/Product/Create",
data: fromData,
method: "post",
dataType: "json",
success: function (response) {
var data = response;
if (data.success) {
$("#modal_sm").modal("hide");
toastr.success("Data success input");
window.location.reload();
}
else {
$("#modal_sm").modal("hide");
toastr.error("Data failed input");
}
}
});
}
I hope can run ajax without get throw to page json result
I guess you used <input type="submit"/> or <button></button> which will automatically submit the form when it is clicked.
Here is a whole working demo:
Model
public class VMProduct
{
public string Name { get; set; }
public int Age { get; set; }
public IFormFile ImageFile { get; set; }
}
public class VMResponse
{
public bool Success { get; set; }
public string Message { get; set; }
}
View
#model VMProduct
<form>
<input type="file" asp-for="ImageFile" />
<input asp-for="Age" />
<input asp-for="Name" />
<input type="submit" value="Post"/>
</form>
#section Scripts
{
<script>
$('form').on('submit', function(e) {
var submittedform = $(this);
e.preventDefault(); //be sure add this if you use submit button
submitAJAX(submittedform);
});
function submitAJAX(form) {
var fromData = new FormData();
var dataForm = $(form).serializeArray();
$.each(dataForm, function (key, input) {
fromData.append(input.name, input.value);
});
var file = $("#ImageFile").prop("files");
if (file.length > 0) {
fromData.append("ImageFile", file[0]);
}
$.ajax({
url: "/Product/Create",
data: fromData,
method: "post",
contentType: false, //be sure add this...
processData: false, //be sure add this...
dataType: "json",
success: function (response) {
var data = response;
if (data.success) {
//do your stuff...
}
else {
//do your stuff...
}
}
});
}
</script>
}

How can I update model view data in jquery?

How can the model data for the page be updated? I want to take full advantage of its presence
in view
#model List<Table.Invoice_Details>
#foreach (Table.Invoice_Details invoice_Details in Model)
{
#Html.TextBoxFor(modelitem => invoice_Details.ID_Invoice_Details, new { id = "ID_Invoice_Details-" + invoice_Details.ID_Invoice_Details })
#Html.TextBoxFor(modelitem => invoice_Details.Sale_Price, new { id = "Sale_Price-" + invoice_Details.ID_Invoice_Details })
<button id="btnSave-" + #invoice_Details.ID_Invoice_Details>save</button>
}
in script :
<script>
$('button[id*=btnSave-]').click(function ()
{
var FullID = $(this).attr('id');
var ID_Number = ID.substring(FullID.indexOf('-') + 1);
var Sale_Price = $('Sale_Price-' + ID_Number).val();
$.get(
{
url: '/Invoice/SaveInvoice',
contents: 'application/json; charset=utf-8',
type: 'post',
dataType: 'json',
data: { ID_Invoice_Details: ID_Number, Sale_Price: Sale_Price },
success: function (result) {
//[Here I want to update model with the new data]
}
})
})
</script>
controller :
private Table.Smart_PosEntities Cn = new Table.Smart_PosEntities();
public JsonResult SaveInvoice(int ID_Invoice_Details, int Sale_Price)
{
Table.Invoice_Details invoice_Details = Cn.Invoice_Details.Where(L => L.ID_Invoice_Details == ID_Invoice_Details).FirstOrDefault();
invoice_Details.Sale_Price = Sale_Price;
Cn.SaveChanges();
return Json(new
{
ID_Invoice_Details = ID_Invoice_Details,
Sale_Price = Sale_Price
}
, JsonRequestBehavior.AllowGet);
}
I just want to update the new data to #Model, to take full advantage
of its presence and also to use it in the calculations, since in the
control there is a column showing the row sum after multiplying by the
quantity, and I don't want to use the calculations in jquery
The best way to update a part of the view with ajax is to use partialview.
1.add class JsonData
public class JsonData
{
public string HtmlMsg { get; set; }
public string HtmlBody { get; set; }
public bool Success { get; set; }
}
2.add ViewHelper class
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
public static class ViewHelper
{
public static string RenderPartialToString(this ControllerBase controller, string partialViewName, object model)
{
IView view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName).View;
return RenderViewToString(controller, view, model);
}
public static string RenderViewToString(this ControllerBase controller, IView view, object model)
{
using (var writer = new StringWriter())
{
controller.ViewData.Model = model;
var viewContext = new ViewContext(controller.ControllerContext, view, controller.ViewData, controller.TempData, writer);
view.Render(viewContext, writer);
return writer.GetStringBuilder().ToString();
}
}
}
3.change SaveInvoice to :
public JsonResult SaveInvoice(int ID_Invoice_Details, int Sale_Price)
{
Table.Invoice_Details invoice_Details = Cn.Invoice_Details.Where(L => L.ID_Invoice_Details == ID_Invoice_Details).FirstOrDefault();
invoice_Details.Sale_Price = Sale_Price;
Cn.SaveChanges();
var model = //fill list
return Json(new JsonData()
{
HtmlMsg = "",
HtmlBody = this.RenderPartialToString("_MyPartial", model),
Success = true,
});
}
4.in your view change to
#model List<Table.Invoice_Details>
<div id="myPartial">
#Html.Partial("_MyPartial", Model)
</div>
5.add partialview _MyPartial
#model List<Table.Invoice_Details>
#foreach (Table.Invoice_Details invoice_Details in Model)
{
#Html.TextBoxFor(modelitem => invoice_Details.ID_Invoice_Details, new { id = "ID_Invoice_Details-" + invoice_Details.ID_Invoice_Details })
#Html.TextBoxFor(modelitem => invoice_Details.Sale_Price, new { id = "Sale_Price-" + invoice_Details.ID_Invoice_Details })
<button id="btnSave-#invoice_Details.ID_Invoice_Details">save</button>
}
6.change script to
$('button[id*=btnSave-]').click(function() {
var FullID = $(this).attr('id');
var ID_Number = FullID.substring(FullID.indexOf('-') + 1);
var Sale_Price = $('Sale_Price-' + ID_Number).val();
$.get({
url: '/Invoice/SaveInvoice',
contents: 'application/json; charset=utf-8',
type: 'post',
dataType: 'json',
data: {
ID_Invoice_Details: ID_Number,
Sale_Price: Sale_Price
},
success: function(result) {
$("#myPartial").html(result.HtmlBody);
}
});
})

Pull data that has just been stored into a database using only one button

I'm creating my very own marketing funnel for my website. How do I get the id of the record I've just saved onto my ajax call without having to use any additional buttons or user triggered methods.
I have created a modal which shows after a user registers their details onto our system as way of the system to interact with the user. Anyway, from this stage onwards, there should be multiple questions being asked to the user about their preferences and the products they want. In my head this just means that I should be updating that user's information the minute that first modal pops up.
Ajax call for saving user info:
$("#btn-save-client").click(function () {
var clientData = {
id: $('#id').val(),
firstName: $('#FirstName').val(),
lastName: $('#LastName').val(),
cellNo: $('#CellNo').val(),
emailAddress: $('#EmailAddress').val(),
country: $('#Country').val()
};
$.ajax({
type: "POST",
url: '/Home/SaveClientData',
data: JSON.stringify(clientData), //Serialises the form's elements.
contentType: "application/json",
dataType: "json",
beforeSend: function () {
$("#contactForm").append('<div class="overlay"><span class="fa fa-refresh fa-spin"></span></div>');
},
success: function (data) {
$("#contactForm .overlay").remove();
$("#contactForm")[0];
LoadFirstFunnel(data.id);
},
error: function (error) {
console.log(error);
console.log(error.responseText);
alert(error.responseText);
},
completed: function () {
$("#contactForm .overlay").remove();
}
});
});
C# method for saving in HomeController.cs:
[System.Web.Mvc.HttpPost]
public ActionResult SaveClientData([FromBody]ClientData clientDataModel)
{
if (clientDataModel == null) return new JsonResult(new {id = null, error = "Please fill in all the details required."});
var _addClientData = new HomeTransactions(new PetaConnection().db()).SaveClient(clientDataModel);
return new JsonResult(new { id = _addClientData.id, error = null });
}
From my HomeController.cs, my code goes to the following code to save data into the database and then return values:
public string SaveClient(ClientData clientDataModel)
{
try
{
ClientInfo clientModel = new ClientInfo();
ClientCompanyInfo clientCompanyModel = new ClientCompanyInfo();
if (clientModel.id == 0 && clientCompanyModel.id == 0)
{
clientCompanyModel.CompanyName = "Default Inc.";
_connect.Save(clientCompanyModel);
Random rand = new Random();
int randomNo = rand.Next(10000, 20000);
string referenceNo = "MTP-" + randomNo;
clientModel.ReferenceNo = referenceNo;
clientModel.FirstName = clientDataModel.FirstName;
clientModel.LastName = clientDataModel.LastName;
clientModel.CellNo = clientDataModel.CellNo;
clientModel.EmailAddress = clientDataModel.EmailAddress;
clientModel.Country = clientDataModel.Country;
clientModel.companyId = clientCompanyModel.id;
clientModel.Active = 1;
clientModel.DateAdded = DateTime.Now;
clientModel.DateUpdated = DateTime.Now;
_connect.Save(clientModel);
clientDataModel.id = clientModel.id;
}
return clientModel.id.ToString();
}
catch (Exception ex)
{
throw;
}
}
Ajax call for LoadFirstFunnel mentioned in the previous Ajax call.
function LoadFirstFunnel(clientId) {
$.ajax({
type: "POST",
url: '/Home/_OpenFirstPanelModal',
data: { clientId: clientId }, // serializes the form's elements.
beforeSend: function (data) {
$("#MessageBoxModal").append('<div class="overlay"><span class="fa fa-refresh fa-spin"></span></div>');
},
success: function (data) {
id = data.id;
$("#MessageBoxModal .overlay").remove();
$('#MessageBoxModal .modal-title').html('Your information was successfully added.');
$('#MessageBoxModal .btn-style-one').attr('id', 'btn-notification');
$('#MessageBoxModal .btn-style-one').attr('id', 'btn-deny-note');
$('#MessageBoxModal .btn-style-one').attr('data-id', '');
$('#MessageBoxModal #regNote').html(data);
$('#MessageBoxModal .modal-dialog').css('width', '');
$('#MessageBoxModal').modal({
backdrop: 'static',
keyboard: false,
show: true
});
},
error: function (xhr, status, error) {
$("#MessageBoxModal .overlay").remove();
alert(error);
},
completed: function (data) {
$("#MessageBoxModal .overlay").remove();
}
});
};
C# call on HomeController.cs which responds to the LoadFirstFunnel ajax call:
public ActionResult _OpenFirstPanelModal(int clientId)
{
ClientInfo _openClientInfoModel = new ClientInfo();
_openClientInfoModel = new HomeTransactions(new PetaConnection().db()).OpenClientInfo(clientId);
return PartialView("_OpenFirstPanelModal", _openClientInfoModel);
}
Modal.cshtml that pops up after registration:
#model MotseThePowerHouse_Website.Models.ClientInfo
<div class="row">
<input type="hidden" value="#Model.id" name="id" />
<div class="text-muted text-center col-sm-12" id="msgDisplay">
<h4>Some text here...</h4>
<h4>Some text here...</h4>
</div>
</div>
<div class="row">
<a id="btn-notification" data-id="#Model.id" class="theme-btn btn-style-one">Yes, notify me</a>
<a id="btn-deny-note" data-id="#Model.id" class="theme-btn btn-style-one">No, thank you</a>
</div>
I know this is all jumbled and it is not working although the logic could make sense, I want to know of other methods out there which can be used by me to deliver this funnel output.
Below is my ClientInfo Model:
using System;
namespace MotseThePowerHouse_Website.Models
{
public class ClientInfo
{
public int id { get; set; }
public string ReferenceNo { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UnitNo { get; set; }
public string UnitStreetName { get; set; }
public string ComplexNo { get; set; }
public string ComplexName { get; set; }
public string StreetName { get; set; }
public string Suburb { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Province { get; set; }
public string Country { get; set; }
public string CellNo { get; set; }
public string TelephoneNo { get; set; }
public string EmailAddress { get; set; }
public string Website { get; set; }
public string BlogNotification { get; set; }
public int companyId { get; set; }
public string PositionHeld { get; set; }
public string OfficeLocation { get; set; }
public DateTime DateAdded { get; set; }
public string UpdatedBy { get; set; }
public DateTime DateUpdated { get; set; }
public int Active { get; set; }
}
}
Create a class which will represent your request body:
public class ClientData
{
public string FirstName {get;set;}
public string LastName {get;set;}
public string CellNo {get;set;}
public string EmailAddress {get;set;}
public string Country {get;set;}
}
Modify your SaveClientData method to the following:
[HttpPost]
public ActionResult SaveClientData([FromBody]ClientData clientData)
{
if (clientDataModel == null) return Json(new {error = "Please fill in all the details required."}, JsonRequestBehavior.AllowGet);
var _addClientData = new HomeTransactions(new PetaConnection().db()).SaveClient(clientDataModel);
return Json(new {id = _addClientData}, JsonRequestBehavior.AllowGet);
}
and your JavaScript code:
var clientData = {
firstName : $('#FirstName').val(),
lastName: $('#LastName').val(),
cellNo: $('#CellNo').val(),
emailAddress: $('#EmailAddress').val(),
country: $('#Country').val()
}
$.ajax({
...
data: JSON.stringify(clientData),
contentType:"application/json",
success: function(data){
if(data.error) { return;}
$("#contactForm .overlay").remove();
$("#contactForm")[0];
LoadFirstFunnel(data.id);
}
});
and for the second part you have to modify the parameter name from id to clientId:
public ActionResult _OpenFirstPanelModal(int clientId)

Get JSON data from Controller to Dropdown in View

I am new to MVC and do not know how to solve this problem.
In a controller I have a list (filled with Api data) serialized to JSON, I need to use this JSON data do populate a dropdown in a View.
I am confused as to what should I return from the controller, what should I be doing next, am I doing this right?
For now I have this:
Model:
public class Tablet {
public int Id { get; set; }
public string ManufactureDate { get; set; }
public string Description { get; set; }
public string Country { get; set; }
}
DataController.cs
Public ActionResult GetData(Tablet tablet)
{
List<Tablet> data = new List<Tablet>();
// ... Code to retrieve the data from API
string jsonRes = JsonConvert.SerializeObject(data);
return View(jsonRes);
}
In the view I need to show the ID in a dropdown:
View.cshtml
<select class="dropdown" id="dropdownData"></select>
<script>
$(document).ready(function () {
$.ajax({
url: "/Data/GetData/",
type: 'GET',
success: function (jsonRes) {
console.log(jsonRes[i]);
var s = '<option value="-1">Please Select</option>';
for (var i = 0; i < jsonRes.length; i++) {
s += '<option value="' + jsonRes[i].Id+ '">' + '</option>';
}
$("#dropdownData").html(s);
}
});
});
</script>
Try this, you are setting Value, you are not setting Text for Option Tag, you must be getting blank menu items.Have tested it using your data link and code.
s += '<option value="' + jsonRes[i].Id+ '">'+jsonRes[i].Id + '</option>';
Complete HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<select class="dropdown" id="dropdownData"></select>
<script>
$(document).ready(function () {
$.ajax({
url: "https://api.myjson.com/bins/6jd1s",
type: 'GET',
success: function (jsonRes) {
console.log(jsonRes[i]);
var s = '<option value="-1">Please Select</option>';
for (var i = 0; i < jsonRes.length; i++) {
s += '<option value="' + jsonRes[i].Id+ '">'+jsonRes[i].Id + '</option>';
}
$("#dropdownData").html(s);
}
});
});
</script>
</body>
</html>
Try this:
DataController:
[HttpGet]
public JsonResult GetData()
{
List<Tablet> data = new List<Tablet>();
// ... Code to retrieve the data from your API
string jsonRes = JsonConvert.SerializeObject(data);
return new JsonResult(jsonRes);
}
In your JavaScript:
$.ajax({
url: "/Data/GetData/",
type: "GET",
dataType: "json",
cache: false,
success: function (data) {
try {
var parsedData = JSON.parse(data);
var $select = $('#dropdownData');
$.each(parsedData, function(i, dataItem) {
$('<option>', {
value: dataItem.Id
}).html(dataItem.Id).appendTo($select); // or dataItem.Description, or whatever field you want to display to the user
});
}
catch (err) {
console.log(err);
}
}
},
error: function (e) {
console.log(e);
}
});
Remove the line string jsonRes = JsonConvert.SerializeObject(data);
Also your method GetdData() should return JSON. Check the following code.
public ActionResult GetData(Tablet tablet)
{
List<Tablet> data = new List<Tablet>();
data.Add(new Tablet() { Id = 1, Country = "India", Description = "Test", ManufactureDate = DateTime.UtcNow.ToShortDateString() });
data.Add(new Tablet() { Id = 1, Country = "Canada", Description = "Test1", ManufactureDate = DateTime.UtcNow.ToShortDateString() });
//string jsonRes = JsonConvert.SerializeObject(data);
return Json(data,JsonRequestBehavior.AllowGet);
}
View Should be like
<select class="dropdown" id="dropdownData"></select>
<script>
$(document).ready(function () {
$.ajax({
url: "/Home/GetData/",
type: 'GET',
dataType: "json",
success: function (jsonRes) {
console.log(jsonRes[i]);
var s = '<option value="-1">Please Select</option>';
for (var i = 0; i < jsonRes.length; i++) {
s += '<option value="' + jsonRes[i].Id + '">' + jsonRes[i].Id+ '</option>';
}
$("#dropdownData").html(s);
}
});
});
</script>

KnockoutJS observable not accessible via Controller MVC

I'm stuck on an issue. I am trying to access an observable Value from my controller. The data is stored in a JSON object. What's the best way to access it from a controller.
This is my VM
var urlPath = window.location.pathname;
var CreateSalesVM = {
Image :ko.observable({
base64StringArray: ko.observableArray()
}),
btnCreateSales: function () {
console.log("Ko is ", ko.toJSON(this));
$.ajax({
url: urlPath,
type: 'post',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function (result) {
console.log("This was a success");
// window.location.href = urlPath + '/';
alert(ko.toJSON(this));
console.log("Ko is ", ko.toJSON(this));
},
error: function (err) {
console.log("Ko is ", ko.toJSON(this));
if (err.responseText == "success")
{
console.log("This was an error success", urlPath);
// window.location.href = urlPath + '';
}
else {
alert(err.responseText);
// console.log("This was an error ", urlHostPath );
}
},
complete: function () {
}
});
}
};
ko.applyBindings(CreateSalesVM);
This is the controller
public ActionResult Create()
{
return View();
}
// POST: Sales/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
public string Create(SALE_ITEMS sALE_ITEMS)
{
//used for testing since image won't come over
byte[] test = Encoding.ASCII.GetBytes("1232434234");
try
{
var sALE_ITEM_IMAGES = new SALES_ITEM_IMAGES();
Debug.Write("SALES DATA is", sALE_ITEMS);
db.SALE_ITEMS.Add(sALE_ITEMS);
db.SaveChanges();
// Getting id from primary to store record in foreign
decimal newID = sALE_ITEMS.SALE_ID;
Debug.Write("SALES DATA is", newID.ToString());
sALE_ITEM_IMAGES.SALE_ITEM_ID = newID;
//This is where I need to grab the base64 and store it inside sALE_ITEM_IMAGES.IMAGE
sALE_ITEM_IMAGES.IMAGE = sALE_ITEMS.IMAGE;
// Do whatever you need to here
db.SALES_ITEM_IMAGES.Add(sALE_ITEM_IMAGES);
db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.PropertyName + ": " + x.ErrorMessage));
Debug.Write(errorMessages);
}
return "success";
}
Here are my Models
public partial class SALE_ITEMS
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public SALE_ITEMS()
{
this.SALES_ITEM_IMAGES = new HashSet<SALES_ITEM_IMAGES>();
}
public decimal SALE_ID { get; set; }
public string USERID { get; set; }
public string NAME { get; set; }
public string PHONE { get; set; }
public string EMAIL { get; set; }
public string ITEM { get; set; }
public string DESCRIPTION { get; set; }
public string ADMIN_APPROVAL { get; set; }
public Nullable<System.DateTime> CREATED_AT { get; set; }
public Nullable<System.DateTime> UPDATED_AT { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<SALES_ITEM_IMAGES> SALES_ITEM_IMAGES { get; set; }
}
}
and
public partial class SALES_ITEM_IMAGES
{
public decimal ID { get; set; }
public decimal SALE_ITEM_ID { get; set; }
public byte[] IMAGE { get; set; }
public Nullable<System.DateTime> CREATED_AT { get; set; }
public virtual SALE_ITEMS SALE_ITEMS { get; set; }
}
Again, all I'm trying to do is access the base64 IMAGE bind from my Controller.
your view model CreateSalesVM at the client should match the same property names with server side model.
i modified your code, try this
// client side
var urlPath = window.location.pathname;
var CreateSalesVM = {
SALES_ITEM_IMAGES: ko.observableArray([{ //same as ICollection at server side
IMAGE: ko.observableArray([]) // same as byte[] at server side
}]),
btnCreateSales: function() {
var data = ko.toJSON(this);
console.log("Ko is ", data);
$.ajax({
url: urlPath,
type: 'post',
dataType: 'json',
data: data,
contentType: 'application/json',
success: function(result) {
console.log("This was a success");
// window.location.href = urlPath + '/';
console.log(result);
},
error: function(err) {
console.log("Ko is ", data);
if (err.responseText == "success") {
console.log("This was an error success", urlPath);
// window.location.href = urlPath + '';
} else {
alert(err.responseText);
// console.log("This was an error ", urlHostPath );
}
},
complete: function() {}
});
}
};
ko.applyBindings(CreateSalesVM);
and
// server side
[HttpPost]
public string Create(SALE_ITEMS item)
{
try
{
Debug.Write("SALES DATA is", item);
db.SALE_ITEMS.Add(item);
db.SaveChanges();
// Getting id from primary to store record in foreign
decimal newID = item.SALE_ID;
Debug.Write("SALES DATA is", newID.ToString());
// loop Images
foreach (var image in item.SALE_ITEM_IMAGES)
{
image.SALE_ITEM_ID = newID;
// Do whatever you need to here
db.SALES_ITEM_IMAGES.Add(image);
db.SaveChanges();
}
}
catch (DbEntityValidationException ex)
{
string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.PropertyName + ": " + x.ErrorMessage));
Debug.Write(errorMessages);
}
return "success";
}

Categories

Resources