如何将动态创建的元素发布到数据库MVC c#

时间:2017-04-02 12:58:03

标签: c# asp.net-mvc-4

美好的一天,我用jquery动态创建了表单元素,如下所示:

<label for="fname" class="fname_label col-sm-2 control-label">First Name</label>
<div class="col-sm-4">
    <input type="text" class="fname_input form-control" id="fname" placeholder="First Name" name="firstnames">
</div>

<label for="uemail" class="uemail_label col-sm-2 control-label">Email</label>
<div class="col-sm-4">
    <input type="text" class="uemail_input form-control" id="uemail" placeholder="Email" name="emailaddresses">

用户可以使用相同的名称和ID创建多个这样的元素。我的意思是如果用户应该单击添加更多,则使用jquery创建具有相同名称和id的相同元素。用户可以创建多个元素,例如10个或更多。我的问题是如何将动态创建元素的值发布或插入到数据库中。我在MVC中使用c#。谢谢。

1 个答案:

答案 0 :(得分:1)

有一点时间把它放在一起。我创建了一个JavaScript命名空间来保存我的函数,数据等;保持jQuery部分为事件(提交和添加行)管理分开。您可以轻松添加删除新条目组(行)的功能,只需要一个逗留,因为我使用.clone()来获取新行。

使用一些引导程序的示例标记(功能部件不需要)。注意我使用jQuery作为ajax的东西,你不必这么做,但它可能会使样本变小。

<div class="container">
  <form id="myform">
    <div class="inputs-holder">
      <fieldset class="entry-group">
        <legend class="col-form-legend col-xm-2">
          one input
        </legend>
        <div class="form-group row">
          <label class="col-xs-2 col-form-label col-form-label-sm">Name</label>
          <div class="col-xs-7">
            <input required="true" class="form-control form-control-xs name-field" type="text" />
          </div>
        </div>
        <div class="form-group row">
          <label class="col-xs-2 col-form-label col-form-label-sm">Email</label>
          <div class="col-xs-7">
            <input required="true" class="form-control form-control-xs email-field" type="email" placeholder="enter email" value="testme@example.com" />
          </div>
        </div>
      </fieldset>
    </div>
    <div class="form-group row">
      <div class="offset-xs-2 col-xs-5">
        <button id="submitme" type="submit" class="btn btn-primary btn-xs">Submit Me</button>
      </div>
      <div class="offset-xs-2 col-xs-5">
        <button id="addnewgroup" type="button" class="btn btn-xs">Add new group</button>
      </div>
    </div>
  </form>
</div>
<div id="results">
  Entries
</div>

一些脚本要处理并通过ajax将数据推送到服务器:

/* Latest compiled and minified JavaScript included as External Resource */

var myApp = myApp || {};
myApp.arrayObj = {
  // some stuff clipped out not used here...
  // use to lookup duplicates
  lookup: function(myArray, searchTerm, property, firstOnly) {
    var found = [];
    var i = myArray.length;
    while (i--) {
      if (myArray[i][property] === searchTerm) {
        found.push(myArray[i]);
        if (firstOnly) break; //if only the first 
      }
    }
    return found;
  },
  // could be used to validate duplicates for example
  lookupAll: function(myArray, property, searchTerm) {
    return this.lookup(myArray, searchTerm, property, false);
  }
};
myApp.data = {
  entries: [],
  saveUrl: "/Home/SaveEmails" this COULD be from server/MVC
};
myApp.func = {
  addEmailRow: function(myArray, item, allowdups, uniquekey) {
    // matches the  POCO object class names
    var entry = {
      "name": item.name,
      "email": item.email
    };
    if (allowdups || (!allowdups && !myApp.arrayObj.lookup(myArray, entry[uniquekey], uniquekey, true).length)) {
      myArray.push(entry);
    } else if (allowdups && myApp.arrayObj.lookup(myArray, entry[uniquekey], uniquekey, true).length) {
      myApp.data.entries[uniquekey] = item[uniquekey];
    } else if (allowdups && !myApp.arrayObj.lookup(myArray, entry[uniquekey], uniquekey, true).length) {
      myArray.push(entry);
    }
  },
  // just something to show what is entered/being submitted
  showEntries: function(list) {
    $.each(list, function(index, value) {
      $('#results').append("<div>" + value.name + " " + value.email + "</div>");
    });
  },
  // the important part
  saveEntries: function(list) {
    var entries = JSON.stringify({
      'Entries': list
    });

    $.ajax({
        contentType: 'application/json;',
        dataType: 'json',
        type: 'POST',
        url: myApp.data.saveUrl,
        data: entries
      }).done(function() {
        $('#results').html('"SaveEmails()" successfully called.');
      })
      .fail(function(response) {
        $('#results').html(response);
      });
  }
};
$(document).ready(function() {
  // add new "group" row
  $('#addnewgroup').on('click', function() {
    var holder = $('.inputs-holder');
    // clone that first row
    var newRow = holder.find('.entry-group').eq(0).clone();
    // clear any values entered and append it
    newRow.find('input').val("");
    newRow.appendTo(holder);
  });
  // a bit verbose for clarity here
  $('#myform').on('submit', function(e) {
    e.preventDefault();
    e.stopPropagation();
    // clear entries
    myApp.data.entries = [];
    var allowdups = false,
      uniquekey = "name";
    var holder = $('.inputs-holder');
    // get entries
    holder.find('.entry-group').each(function() {
      var email = $(this).find('.email-field').val();
      var name = $(this).find('.name-field').val();
      var item = {
        "email": email,
        "name": name
      };
      myApp.func.addEmailRow(myApp.data.entries, item, allowdups, uniquekey);
    });
    $('#results').html("<div>Results:</div>");
    myApp.func.showEntries(myApp.data.entries);
    myApp.func.saveEntries(myApp.data.entries);

    // supress default submit form
    return false;
  });
});

现在是服务器端:

/* MVC for this: */
// POCO object: - reference this whereever you put it.
public class EmailEntry
{
    public String name { get; set; }
    public String email { get; set; }
}

// controller/ method: used IEnumerable instead of List as simpler
public class HomeController : Controller
{
   [HttpPost]
    public void SaveEmails(IEnumerable<EmailEntry> entries)
    {
        // do stuff with email entries here...validate/save for example
    }
}

所有这些都是未经测试的,我的包含小错误,但我认为它非常无错误。