我想將模型物件的多個實體作為串列發送到控制器,但由于某種原因,串列的計數始終為 1,物件的值始終為 0,因此按下提交時實際上沒有發布任何內容。
這是我的觀點:
@model List<MVCModel.Models.Student>
<b>Items</b> @ViewBag.Items <br />
<b>Value</b> @ViewBag.Value <br />
@using (Html.BeginForm("Form", "Home", FormMethod.Post))
{
<table>
<tbody id="GenaratorList">
<tr>
@{
int counter = 0;
<td>Enter Name: </td>
<td>@Html.TextBoxFor(m => m[counter].Name, new {id = "Name"})</td>
<td>Enter Age: </td>
<td>@Html.TextBoxFor(m => m[counter].Age, new {id = "Age"})</td>
<td><input type="button" value="Add" onclick="addGenarator()" /></td>
</tr>
counter ;
}
<tbody>
</table>
<input type="submit" value="Submit Form"/>
}
<script>
count = 0;
function addGenarator() {
var Name = $('#Name').val();
var Age = $('#Age').val();
var Student = "studentModels[" count "]";
$('#GenaratorList').append('<tr><td><input id="' Student '.Name" Name="' Student '.Name" type="text" readonly value="' Name '"></td><td><input id="' Student '.Age" Age="' Student '.Age" type="text" readonly value="' Age '"></td></tr>');
$('#Name,#Age').val('');
count ;
}
</script>
這是我的控制器:
[HttpPost]
public ActionResult Form(List<Student> s)
{
ViewBag.Items = s.Count; // ALWAYS RETURNS 1
ViewBad.Value = s[0].Age // TEST VALUE OF FIRST ITEM RETURNS 0
return View("Index");
}
這是我的模型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCModel.Models
{
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
}
uj5u.com熱心網友回復:
您的Form(HttpPost) API 應該會收到一個請求正文,其中包含一個名為s. 您將studentModels根據您的 JS 代碼將陣列作為 (name) 傳遞。
var Student = "studentModels[" count "]";
而且您錯過了每個 Age 輸入的 name 屬性。
<input id="' Student '.Age" Age="' Student '.Age" type="text" class="form-control" readonly value="' Age '">
要解決此問題,請確保 View 中的陣列名稱必須與 Controller 引數名稱匹配。對于下面的代碼,我將陣列命名s為與 Controller API 預期引數名稱相同的名稱。
此外,應用
除錯輸出

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/495005.html
標籤:javascript C# 网 asp.net-mvc asp.net-mvc-5
