jquery
  • asp.net-mvc-3
  • knockout.js
  • 2012-03-25 11 views 3 likes 
    3

    Ich habe eine Form wie diese:asp MVC3, Post Form mit versteckter Eingabe enthält json Array

    <form id="orderForm"> 
        <input name="Customer" value="Mr.Test" /> 
        <input name="ProductLines" value='[{"Product":{"Name":"Orange","Price":"10"},"amount":"2","total":"20"}, {"Product":{"Name":"Apple","Price":"5"},"amount":"3","total":"15"}]' /> 
    </form> 
    

    und Regler mit Blick Modellen:

    [HttpPost] 
    public ActionResult Save(OrderViewModel vm) 
    { 
        //... 
    } 
    
    public class OrderViewModel 
    { 
        public OrderViewModel() { ProductLines = new List<OrderProductViewModel>(); } 
        public string Customer { get; set; } 
        public IEnumerable<OrderProductViewModel> ProductLines { get; set; } 
    } 
    
    public class OrderProductViewModel 
    { 
        public ProductViewModel Product { get; set; } 
        public int Amount { get; set; } 
        public int Total { get; set; } 
    } 
    
    public class ProductViewModel 
    { 
        public string Name { get; set; } 
        public int Price { get; set; } 
    } 
    

    ist es möglich, diese Form mit hinterlassen jquery

     $.post('@Url.Action("Save")', $("#orderForm").serialize(), function (data) {//...}, "json"); 
    

    und Get ProductLines Sammlung auf Server-Seite gefüllt. (momentan ist es immer leer)

    Danke!

    Antwort

    2

    Das Buchungsobjekt muss in json-Objekt konvertiert und mit dem Inhaltstyp json gepostet werden. Versuchen Sie Folgendes, es könnte helfen

    var results = {}; 
    $.each($("#orderForm").serializeArray(), function (index, item) { 
        results[item.name] = item.value; 
    }); 
    results.ProductLines = $.parseJSON(results.ProductLines); 
    $.ajax({ 
        url: '@Url.Action("Save")', 
        type: 'post', 
        data: JSON.stringify(results), 
        contentType: "application/json; charset=utf-8", 
        dataType:'json', 
        success: function (data) { 
         alert("hi"); 
        } 
    }); 
    
    +0

    ty Sir! Das hat funktioniert :) – shkipper

    +0

    Sie sind willkommen. :) – shakib

    Verwandte Themen