2017-04-02 30 views
0

美好的一天,我已動態創建表單元素,看起來像這樣:使用jQuery如何發佈動態創建的元素以數據庫MVC C#

<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

重複的'id'屬性是無效的html。要綁定到一個集合,您的輸入需要收集索引器。請參閱[這個答案](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308)一些例子 –

+0

首先閱讀規範來理解爲什麼這不是有效的方案https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute這涵蓋了名稱屬性https:// www。 w3.org/TR/html401/interact/forms.html#h-17.2 –

+0

請注意,您所描述的內容在規範中也稱爲「成功控件」:https://www.w3.org/TR/html401/interact /forms.html#successful-controls –

回答

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="[email protected]" /> 
      </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 
    } 
} 

ALL這是未經測試,我的包含小錯誤,但我相信它是相當無bug的。

相關問題