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";
}
Related
I'm trying to save data in my database using Javascript but always receive the same error. Im using MVC and send data using axios
.NET has a form to access to my request data and manipulate as I want?
Model
public class Pensionado
{
public int Id { get; set; }
[Required]
public int No_activo { get; set; }
public bool Cobro_indebido { get; set; }
[Required]
public bool Status_pago { get; set; }
[Required]
public int Clave_pension { get; set; }
[Required]
public int No_afiliado { get; set; }
[Required]
public int No_pension { get; set; }
[Required]
public bool Sexo { get; set; }
[MaxLength(50)]
[Required]
public string ApellidoP { get; set; }
[MaxLength(50)]
[Required]
public string ApellidoM { get; set; }
[MaxLength(50)]
[Required]
public string Nombre { get; set; }
[Required]
public DateTime Fecha_nacimiento { get; set; }
[MaxLength(13)]
[Required]
public string RFC { get; set; }
[MaxLength(18)]
[Required]
public string CURP { get; set; }
[MaxLength(50)]
[Required]
public string Email { get; set; }
public int Estado_civilId { get; set; }
public Estado_civil estado_Civil { get; set; }
public int Tipo_PensionId { get; set; }
public Tipo_Pension tipo_Pension { get; set; }
}
I tried omitting FromBody but I received the same error
[HttpPost]
public async Task<ActionResult<Pensionado>> Post([FromBody] Pensionado pensionado)
{
var usuarioId = servicesUsuario.ObtenerUsuarioId();
var pensionadoBD = new Pensionado
{
No_activo = pensionado.No_activo,
Cobro_indebido = pensionado.Cobro_indebido,
Clave_pension = pensionado.Clave_pension,
No_afiliado = pensionado.No_afiliado,
No_pension = pensionado.No_pension,
Sexo = pensionado.Sexo,
ApellidoP = pensionado.ApellidoP,
ApellidoM = pensionado.ApellidoM,
Nombre = pensionado.Nombre,
Fecha_nacimiento = pensionado.Fecha_nacimiento,
RFC = pensionado.RFC,
CURP = pensionado.CURP,
Estado_civilId = pensionado.Estado_civilId,
Tipo_PensionId = pensionado.Tipo_PensionId,
Email = pensionado.Email
};
context.Add(pensionadoBD);
await context.SaveChangesAsync();
return pensionado;
}
Javascript post function
export const guardarPensionado = async (url, data) => {
return http.POST(url, data)
.then((res => { }))
.catch(error => {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
console.log(error.config);
console.log(error)
throw new Error('A ocurrido un error.', error)
})
}
Index script where I call POST function
btnGuardar.addEventListener('click', async () => {
try {
const data = obtenerDatosFormulario()
await guardarPensionado(UrlApiBase, data);
alert('Se guardo al pensionado');
} catch (error) {
console.log(error)
}
});
//Return the data correctly
const obtenerDatosFormulario = () => {
return {
No_activo: parseInt(formPensionado.no_activo.value),
Status_pago: 0,
Clave_pension: parseInt(formPensionado.clave_pension.value),
No_afiliado: parseInt(formPensionado.no_afiliado.value),
No_pension: parseInt(formPensionado.no_pension.value),
Sexo: parseInt(d.querySelector('input[name=sexo]:checked').value) || 0,
ApellidoP: formPensionado.apellidoP.value,
ApellidoM: formPensionado.apellidoM.value,
Nombre: formPensionado.nombre.value,
Fecha_nacimiento: formPensionado.fecha_nacimiento.value,
RFC: formPensionado.rfc.value,
CURP: formPensionado.curp.value,
Email: formPensionado.email.value,
Estado_civilId: parseInt(formPensionado.estado_civil.value),
Tipo_PensionId: parseInt(formPensionado.tipo_pensiones.value),
Cobro_indebido: formPensionado.cobre_indebido.checked
}
}
Update:
Based on your comment, I think you are having a little mess while sending request. I have simulate your issue both in client side and Backend both worked as expected. here is the takeaways:
When Submit As [FromBody]:
Let's assume, you want to submit request from client-side as [FromBody] for instance,
[HttpPost]
public async Task<ActionResult<Pensionado>> Post([FromBody] Pensionado pensionado)
{
... Your Code
}
In above scenario, you should submit request as below:
var data = {
Id: 101,
No_activo: 1,
Cobro_indebido: true,
ApellidoP: "Test P ",
ApellidoM: "Test M ",
}
console.log(data);
$.ajax({
type: "POST",
url: "http://localhost:5094/Controller/Post",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(data),
success: function (res) {
alert(res)
},
error: function (res) {
alert(res)
}
});
Note: Importantly, when submit [FromBody] you must parse your data into JSON.stringify() and set content type explicitly likee contentType: "application/json" either of the violation will submit null data.
When Submit As Class Parameter:
[HttpPost]
public async Task<ActionResult<Pensionado>> Post(Pensionado pensionado)
{
... Your Code
}
In above scenario, you do not need to parse your data explicitely into json like this way JSON.stringify(). However, in this case, you should submit request as below:
var data = {
Id: 101,
No_activo: 1,
Cobro_indebido: true,
ApellidoP: "Test P ",
ApellidoM: "Test M ",
}
console.log(data);
$.ajax({
type: "POST",
url: "http://localhost:5094/EntityJoinRelationship/Post",
dataType: "json",
data: data,
success: function (res) {
alert(res)
},
error: function (res) {
alert(res)
}
});
Note: You can notice, here contentType: "application/json" and JSON.stringify() not required. You just need to pass data as data: data, as your value comes.
Output:
I tried omitting FromBody but I received the same error
Well, the issue is not within yourFromBody, it's in your Pensionado class. If you would like to allow null for column ApellidoM, then you need to get rid of the [Required] annotation from its definition. Assign additional ? like string? to it which tells this property to accept null value.
It should as below:
[MaxLength(50)]
public string? ApellidoM { get; set; }
Note: you should bear in mind that [Required] makes your table schema non-nullable by setting it not null. You can get more detail in the official document here.
## AJAX CALL in cshtml page ##
function ValidateData() {
var editedRows = [];
$("#eventsTable tbody tr").each(function () {
editedRows.push({
PK_WS_Event: $(this).find("td:eq(1)")[0].innerText,
Act_Id: $(this).find("td:eq(2)")[0].innerText,
WeeklyStatus: $(this).find("td:eq(3) option:selected").text()
== "--Select--" ? "" : $(this).find("td:eq(3)
option:selected").text(),
WeeklyStatusSubType: $(this).find("td:eq(4)
option:selected").text() == "--Select--" ? "" : $(this).
find("td:eq(4) option:selected").text(),
AccountName: $(this).find("td:eq(5)")[0].innerText,
AccountNumber: $(this).find("td:eq(6)")[0].innerText,
WeeklyStatusDesc: $(this).find("td:eq(7)")
[0].textContent.trim(),
});
});
$.ajax({
type: 'post',
url: "/WeeklyStatus/IndexSubmit",
data: JSON.stringify({ editedRows: editedRows }),
contentType: 'application/json',
dataType: "html",
success: function (response) {
},
error: function (xhr, status, error) {
alert('fail');
}
});
}
## Server Code Controller and ##
----------
[HttpPost]
public IActionResult IndexSubmit(IList<WeeklyStatusEvents>
editedRows)
{
return null;
}
My ViewModel as like as below..
public class ReportViewModel
{
public int SelectedStatusId { get; set; }
public int SelectedSubTypeId { get; set; }
public List<WeeklyStatusEvents> statusEvents { get; set; }
}
And WeeklyStatusEvents model as shown below
public class WeeklyStatusEvents
{
public string PK_WS_Event { get; set; }
public string Act_Id { get; set; }
//public bool INDExcludeFromRpt { get; set; }
public string WeeklyStatus { get; set; }
public string WeeklyStatusSubType { get; set; }
public string AccountName { get; set; }
public string AccountNumber { get; set; }
public string WeeklyStatusDesc { get; set; }
}
So Here, I am getting count as 0......
I have created class with all these properties. and Same property name I was used in ajax call as well.
Even I am not getting data. Can you provide the solution what i missed to get the data.
Replace
data: JSON.stringify({ editedRows: editedRows }),
with
data: JSON.stringify(editedRows),
The difference is that you want to send an array of objects instead of an object which contains an array.
In order to see the diferences between those two, I recommend you to inspect what the following lines return:
console.log(JSON.stringify(editedRows)
console.log(JSON.stringify({ editedRows: editedRows })
And add [FromBody] in front of your parameter in your action.
Add [FromBody] in front of your List and try again
[HttpPost]
public ActionResult IndexSubmit([FromBody] List<WeeklyStatusEvents> obj)
{
Vreturn null;
}
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)
my entity
public class Agent
{
[Key]
[JsonProperty(PropertyName = "agentId")]
public int AgentId { get; set; }
[JsonProperty(PropertyName = "codeName")]
public string CodeName { get; set; }
[JsonProperty(PropertyName = "firstName")]
public string FirstName { get; set; }
[JsonProperty(PropertyName = "lastName")]
public string LastName { get; set; }
[JsonProperty(PropertyName = "imagePath")]
public string ImagePath { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
}
my Viewmodel
public class AgentVm
{
public int AgentId { get; set; }
public string CodeName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ImagePath { get; set; }
public string Description { get; set; }
}
my Get web api controller
public IQueryable<AgentVm> GetAgents()
{
var agents = from b in db.Agents
select new AgentVm()
{
AgentId = b.AgentId,
FirstName = b.FirstName,
LastName = b.LastName,
CodeName = b.CodeName,
ImagePath = b.ImagePath
};
return agents;
}
my post web api controller
public async Task<HttpResponseMessage> PostAgent(Agent agent)
{
if (agent != null)
{
// Extract the image from the image string
string regEx = "data:(.+);base64,(.+)";
Match match = Regex.Match(agent.ImagePath, regEx);
if (match.Success)
{
// Get the content-type of the file and the content
string imageType = match.Groups[1].Value;
string base64image = match.Groups[2].Value;
if (imageType != null && base64image != null)
{
// Verify the content-type is an image
string imageRegEx = "image/(.+)";
match = Regex.Match(imageType, imageRegEx);
if (match.Success)
{
// Get the file extension from the content-type
string fileExtension = match.Groups[1].Value;
// Get the byte-array of the file from the base64 string
byte[] image = Convert.FromBase64String(base64image);
string path = HttpContext.Current.Server.MapPath("~/images");
string fileName = agent.FirstName + agent.LastName;
// Generate a unique name for the file (add an index to it if it already exists)
string targetFile = fileName + "." + fileExtension;
int index = 0;
while (File.Exists(Path.Combine(path, targetFile)))
{
index++;
targetFile = fileName + index + "." + fileExtension;
}
// Write the image to the target file, and update the agent with the new image path
File.WriteAllBytes(Path.Combine(path, targetFile), image);
agent.ImagePath = "images/" + targetFile;
db.Agents.Add(agent);
await db.SaveChangesAsync();
// Create the Location http header
var response = Request.CreateResponse(HttpStatusCode.Created, agent);
string uri = Url.Link("GetAgent", new { id = agent.AgentId});
response.Headers.Location = new Uri(uri);
return response;
}
}
}
}
throw new HttpResponseException(Request.CreateErrorResponse(
HttpStatusCode.BadRequest, "Could not deserialize agent"));
}
and this is my js
var ViewModel = function() {
var self = this;
self.agents = ko.observableArray();
self.error = ko.observable();
self.agent = ko.observableArray();
self.newAgent = {
FirstName: ko.observable(),
LastName: ko.observable(),
CodeName: ko.observable(),
Description: ko.observable(),
ImagePath: ko.observable()
}
var agentsUrl = "/api/agents/";
function ajaxHelper(uri, method, data) {
self.error(""); // Clear error message
return $.ajax({
type: method,
url: uri,
dataType: "json",
contentType: "application/json",
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllAgents() {
ajaxHelper(agentsUrl, "GET").done(function (data) {
self.agents(data);
});
}
self.addAgent = function (formElement) {
var agent = {
AgentId: self.newAgent.Agent().AgentId,
FirstName: self.newAgent.FirstName(),
LastName: self.newAgent.LastName(),
CodeName: self.newAgent.CodeName(),
Description: self.newAgent.Description(),
ImagePath: self.newAgent.ImagePath()
};
ajaxHelper(agentsUrl, 'POST', agent).done(function (item) {
self.agents.push(item);
});
}
getAllAgents();
};
ko.applyBindings(new ViewModel());
and this is my image element
<img data-bind="attr:{ src: ImagePath }"/>
but the image is not displaying and i can't figure out to add an upload,
please someone help , i don't need angular , just a simple mvvm such as knockout js but am relative new in it.
Look at the generated <img> element with Chrome console, or Firebug from firefox (specially the src property). Then copy the URL in a new tab and check if its displayed. I think your problem is that the element is rendered correctly, but your project cannot render direct images, as MVC will try to use the route logic to find the controller/action you are requesting, returning an HTTP 404. Check this response for a solution
You can create a simple form to upload files, or perhaps you can use jquery $.post, if you want to use ajax. Here is a sample for that
I have the following entity
Entity AssetMgmt
public class AssetMgmt : CommonPropertiesViewModel
{
public int DepartmentId { get; set; }
public int TypeOfDevice { get; set; }
public string DeviceStatus { get; set; }
public test[] Subscriptions { get; set; }
}
Entity test
public class test
{
public string IMEINumber { get; set; }
public int? SubscriptionType { get; set; }
public string SubscriptionTypeName { get; set; }
public int CarrierId { get; set; }
public string CarrierName { get; set; }
public int AccountId { get; set; }
public string PhoneNo { get; set; }
public bool setAsPrimary { get; set; }
public string SIMNo { get; set; }
public string Puk1 { get; set; }
public string Puk2 { get; set; }
public int Id { get; set; }
public decimal Maxbudget { get; set; }
public bool SendConsumption { get; set; }
}
Entity CommonPropertiesViewModel
public class CommonPropertiesViewModel
{
public int Id { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public string CustomMessage { get; set; }
public int ClientId { get; set; }
}
javascript function
function SaveNew() {
var del = { "ClientId" : 0,
"CreatedBy" : null,
"CreatedOn" : "/Date(-62135596800000)/",
"CustomMessage" : null,
"DepartmentId" : 0,
"DeviceStatus" : null,
"Id" : 4,
"ModifiedBy" : null,
"ModifiedOn" : null,
"Subscriptions" : [ { "AccountId" : 421,
"CarrierId" : 1,
"CarrierName" : "Airtel",
"IMEINumber" : "352698040297280",
"Id" : 8,
"Maxbudget" : 250.0,
"PhoneNo" : "9409635039",
"Puk1" : "2415367892",
"Puk2" : "9818067434",
"SIMNo" : "485769351624",
"SendConsumption" : true,
"SubscriptionType" : 1,
"SubscriptionTypeName" : "Voice",
"setAsPrimary" : true
},
{ "AccountId" : 421,
"CarrierId" : 1,
"CarrierName" : "Airtel",
"IMEINumber" : "352276053001012",
"Id" : 9,
"Maxbudget" : 750.0,
"PhoneNo" : "4875351547",
"Puk1" : "9742277228",
"Puk2" : "2789210574",
"SIMNo" : "365289701254",
"SendConsumption" : true,
"SubscriptionType" : 1,
"SubscriptionTypeName" : "Voice",
"setAsPrimary" : true
}
],
"TypeOfDevice" : 1
}
$.ajax({
type: "POST",
url: $("#urlprefix").val() + 'AssetManagement/SaveNew',
data: { "del": JSON.stringify(del) },
success: function (d) {
console.log('here');
return false;
},
error: function (msg) {
}
});
}
After doing all these...
My AJAX Call
[HttpPost]
public ActionResult SaveNew(AssetMgmt del)
{
return View("SaveNew", del);
}
When i hover on highlighted area in debug mode I should get values that are sent from client side to the server.
My problem is that when i make AJAX Call I am getting no value for del. No values are received on server side. I.E. in SaveNew(AssetMgmt del) i get either null or blank object.
What i want is value for del that is sent from client side.
you need to spe4cify the content type as JSON
$.ajax({
type: "POST",
url: $("#urlprefix").val() + 'AssetManagement/SaveNew',
data: JSON.stringify({ del: del }),
contentType: 'application/json',
success: function (d) {
console.log('here');
return false;
},
error: function (msg) {
}
});
you can get value from this way
$.ajax({
type: "POST",
url: $("#urlprefix").val() + 'AssetManagement/SaveNew',
data: JSON.stringify({ del: del }),
contentType: 'application/json',
success: function (d) {
alert(d.del);
console.log('here');
return false;
},
error: function (msg) {
}
});
See this simple example and try that way
This is json function
function SaveNew() {
var AccountId = 421;
$.ajax({
url: 'SaveNew',
type: 'POST',
data: JSON.stringify({ AccountId : AccountId }),
dataType: 'json',
contentType: 'application/json',
success: function (result) {
if(result.del==1)
{
alert('record saved Successfully.');
}
},
error: function () {
alert('Error Occurred');
}
});
}
};
and this is controller code
[HttpPost]
public JsonResult SaveNew(int AccountId )
{
//here is save code
var del=1;
return Json(new { del }, JsonRequestBehavior.AllowGet);
}
This is perfect work now u can add more fields like 'AccountId' and pass to controller.
first add list in Model of all model class
public class AdminList
{
public List<AssetMgmt> ObjAssetMgmtList { get; set; }
public List<test> ObjtestList { get; set; }
public List<CommonPropertiesViewModel> ObjCommonPropertiesList { get; set; }
}
Then
[HttpPost]
public JsonResult SaveNew(int AccountId )
{
AdminList admins1 = new AdminList();
//add list in admins1 whatever u want then return
return Json(new { admins1 }, JsonRequestBehavior.AllowGet);
}
First u take array in javascript function like
function SaveNew() {
var AccountId;
var CarrierId;
var CarrierName;
var del= [];
del[0] = {
AccountId : 421,
CarrierId : 1,
CarrierName: "Airtel"
};
}
$.ajax({
url: 'SaveNew',
type: 'POST',
data: JSON.stringify({ del: del}),
dataType: 'json',
contentType: 'application/json',
success: function (result) {
//Now u get all field value return back that add in del
int id=result.del.AccountId;
},
error: function () {
alert('Error Occurred');
}
});
}
};
Then add in controller
[HttpPost]
public JsonResult SaveNew(AdminList[] del)
{
AdminList admins1 = new AdminList();
//here u can get field that added in del like
int id=del[0].AccountId;
return Json(new { admins1 }, JsonRequestBehavior.AllowGet);
}