2017-06-02 27 views
1

我有一個表單,其中文本框爲動態已填充。用戶可以靈活地使用add刪除 TextBox這是使用JQuery完成的。 我需要將文本框的傳遞給我的控制器上提交。將視圖中的值傳遞給動態填充表單的控制器

這是我的View

@using (Html.BeginForm("Controller", "Admin", FormMethod.Post, new { required = "required" })) 
{ 
    <h4>Add new Q&A</h4> 
    <div id='TextBoxesGroup'> 
     <div id="TextBoxDiv1"> 
      <input type="text" name="Question" id="Question" required placeholder="Question 1" class="form-control" /><br /> 
     </div> 
    </div> 
      <input type="button" name="Add" id="Add" value="Add" class="btn btn-success" /> 
      <input type="button" name="Remove" id="Remove" value="Remove" class="btn btn-danger" /> <br /><br /> 
      <textarea rows="5" name="Answer" id="Answer" placeholder="Answer" required class="form-control"></textarea><br /> 
      @Html.DropDownList("Intent", ViewData["Intent"] as List<SelectListItem>, "Select Intent", new { @class = "form-control", required = "required" }) 
      <br /><input type="text" name="PrimaryEntity" id="PrimaryEntity" placeholder="Primary keyword" required class="form-control" /><br /> 
      <input type="text" name="SecondaryEntity" id="SecondaryEntity" placeholder="Secondary keyword (optional)" class="form-control" /><br /> 
      <input type="submit" name="Submit" id="Submit" class="btn btn-success" /> 
} 

這是我JS外觀

$(document).ready(function() { 
    var counter = 2; 
    $("#Add").click(function() { 
     var newTextBoxDiv = $(document.createElement('div')) 
      .attr("id", 'TextBoxDiv' + counter); 
     newTextBoxDiv.after().html('<input type="text" name="textbox' + counter + 
       '" id="Question' + counter + '" value="" class="form-control" required placeholder="Question ' + counter + 
       '"> <br />'); 
     newTextBoxDiv.appendTo("#TextBoxesGroup"); 
     counter++; 
    }); 

    $("#Remove").click(function() { 
     if (counter == 2) { 
      alert("No more textbox to remove"); 
      return false; 
     } 
     counter--; 
     $("#TextBoxDiv" + counter).remove(); 
    }); 
}); 

很抱歉,如果我聽起來有點扯。剛開始使用MVC!

+1

問題是什麼? –

+1

建議你的答案中研究代碼[這裏](https://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308)和[here](https://stackoverflow.com/questions/40539321/a-partial-view-passing-a-collection-using-the-html-begincollectionitem-helper/40541892#40541892) –

+0

@KateFernando該文本框被填充使用Javascript和我想將這些文本框的值傳遞給Controller。如果能做到這一點,並且我以正確的方式進行,我是無能爲力的? – Kunal

回答

0

您可以創建一個簡單的模型,該模型具有屬性QuestionsList<string>類型和其他所需的屬性。

再從jQuery的你用一個簡單的邏輯可以添加多個文本框:

<input type="text" name="Model.Questions[" + index + "]" id="Model_Questions_" + index /> 

渲染使用:

@for (int i = 0; i < Model.Questions.Count; i++) 
{ 
    @Html.TextBoxFor(x => Model.Questions[i], { .... }) 
} 

當您發佈的形式,在問題文本框中的所有值將被張貼到您的model的問題列表。

注意:我沒有在VS中編寫上述代碼,所以可能會出現一些錯誤,您可以自行修復。

相關問題