动态添加字段并发送JSON

时间:2017-05-03 06:49:43

标签: javascript jquery asp.net json asp.net-mvc

我是JS中的菜鸟。我正在制作ASP.NET MVC应用程序。我有一个局部视图,我想添加一个新产品。

<fieldset>
    <form>
    <legend>Add detail</legend>
    <div>
        <p>
            Select categorie:
            @Html.DropDownList("Categories");
        </p>
    </div>

    <div>
        <p>
            Select brand:
            @Html.DropDownList("Brands");
        </p>
    </div>

    <div>
        <p>
            Model name:
            @Html.EditorFor(model=>model.part.parts_model)
            @Html.ValidationMessageFor(model=>model.part.parts_model)
        </p>
    </div>

    <div>
        <p>
            Price:
            @Html.EditorFor(model=>model.part.parts_price)
            @Html.ValidationMessageFor(model=>model.part.parts_price)
        </p>
    </div>

    <div>
        <p>
            Amount:
            @Html.EditorFor(model=>model.part.parts_amount)
            @Html.ValidationMessageFor(model=>model.part.parts_amount)

        </p>
    </div>

        <div class="details">
            <input type="text" name="details_name" />
            <input type="text" name="details_value" />
            </div>
        <div><p><a class="plus">Add detail</a></p></div>

    <div>
        <input type="file" name="uploadImage" />
    </div>
        </form>

    <div>
        <input type="submit" value="Save" />
    </div>
</fieldset>

用户按“添加详细信息”后,应添加新字段(与“详细信息”类相同)。 用户按“提交”后,必须将新产品发送到服务器端。

我正在尝试添加这样的新字段:

$(function() {
    $('form').on('click', 'a.plus', function() {
        var fld = $(this).closest('div').prev().find('div.details').last(), add=fld.clone().val('');
        fld.after(add)})
})

我正在寻求帮助,谢谢。

编辑: Erdogan Oksuz帮助动态添加字段。我还是不知道,如何将JSON对象发送到服务器端。还有一个,是否有可能用Razor元素做到这一点?

型号:

public class AddPartViewModel
{
    public bs_parts part { get; set; }
    public List<bs_details> detail { get; set; }
    public bs_images image { get; set; }
}

public partial class bs_parts
{
    public bs_parts()
    {
        this.bs_details = new HashSet<bs_details>();
        this.bs_images = new HashSet<bs_images>();
        this.bs_orders = new HashSet<bs_orders>();
    }

    public decimal parts_id { get; set; }
    public decimal parts_category_id { get; set; }
    public decimal parts_brand_id { get; set; }
    public string parts_model { get; set; }
    public double parts_price { get; set; }
    public int parts_amount { get; set; }

    public virtual bs_brands bs_brands { get; set; }
    public virtual bs_categories bs_categories { get; set; }
    public virtual ICollection<bs_details> bs_details { get; set; }
    public virtual ICollection<bs_images> bs_images { get; set; }
    public virtual ICollection<bs_orders> bs_orders { get; set; }
}

public partial class bs_details
{
    public decimal details_id { get; set; }
    public string details_name { get; set; }
    public string details_value { get; set; }
    public decimal details_part_id { get; set; }

    public virtual bs_parts bs_parts { get; set; }
}

我的服务器代码(不要查看ide,它用于测试):

[HttpPost]
    public ActionResult CreatePart(AddPartViewModel model, HttpPostedFileBase uploadImage)
    {
        ViewBag.Categories = new SelectList(_db.bs_categories, "categories_id", "categories_name");
        ViewBag.Brands = new SelectList(_db.bs_brands, "brands_id", "brands_name");
        if (ModelState.IsValid && model.part != null)
        {
            model.part.parts_brand_id = 3;
            model.part.parts_category_id = 3;
            _db.bs_parts.Add(model.part);
            if (model.detail != null)
            {
                foreach (var details in model.detail)
                {
                    details.details_part_id = 8;
                    _db.bs_details.Add(details);
                    _db.SaveChanges();
                }
            }
            if (ModelState.IsValid && uploadImage!=null)
            {
                byte[] imageData = null;
                using (var binaryReader = new BinaryReader(uploadImage.InputStream))
                {
                    imageData = binaryReader.ReadBytes(uploadImage.ContentLength);
                }
                model.image.image_part_id = model.part.parts_id;
                model.image.images_image = imageData;
                _db.bs_images.Add(model.image);

            }
            _db.SaveChanges();
            return RedirectToAction("Main");
        }
        return View(model);
    }

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
var $myForm=$("#myForm");

$(".plus").off("click").on("click",function(){
  $(".details").append(`
    <div class="details-part">
      <input class="details_name" type="text" />
      <input class="details_value" type="text" />
    </div>
  `)
});

$("#save-form").off("click").on("click",function(){
  var detailList=[];
  $myForm.find(".details-part").each(function(){
     detailList.push({
        details_value:$(this).find(".details_value").val(),
        details_name:$(this).find(".details_name").val()
      })
   });
  $myForm.find('[name="details"]').val(JSON.stringify(detailList))
  $myForm.submit()
});
&#13;
.plus{
  cursor:pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form id="myForm" method="post" action="/yourpath">

        <div class="details">
           <div class="details-part">
            <input class="details_name" type="text" />
            <input class="details_value" type="text" />
           </div>
        </div>
        <div><p><a class="plus">Add detail</a></p></div>

    <div>
        <input type="file" name="uploadImage" />
    </div>
        
    <input type="hidden" name="details"/>
    <div>
        <button id="save-form">Save</button>
    </div>
</form>
&#13;
&#13;
&#13;