无法通过Controller MVC访问KnockoutJS observable

时间:2017-02-02 07:14:04

标签: c# asp.net-mvc entity-framework knockout.js

我遇到了问题。我试图从我的控制器访问一个可观察的值。数据存储在JSON对象中。从控制器访问它的最佳方法是什么。

这是我的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);

这是控制器

   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";
    }

以下是我的模特

 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; }
}
}

  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; }
}

同样,我要做的就是从我的Controller访问base64 IMAGE绑定。

1 个答案:

答案 0 :(得分:0)

客户端的视图模型CreateSalesVM应与服务器端模型匹配相同的属性名称。

我修改了你的代码,试试这个

// 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);

// 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";
}