【发布时间】:2020-09-24 03:22:56
【问题描述】:
我有以下具有学生名字和姓氏属性的简单类。 当加载此模型的视图时,我想添加额外的列来为每一行分配与成本相关的信息,因此我在我的 DOT 类中添加了两个字段,即 StudentDoaminModel。
视图加载正常,但每个新属性 Cost1 和 Cost2 的值没有传递给控制器。
我想用ajax把模型传给控制器
学生模型课
public class Student
{
public string first_name{ get; set; }
public string last_name { get; set; }
}
学生领域模型课
public class StudentDomainModel
{
public string first_name{ get; set; }
public string last_name { get; set; }
public int Cost1 { get; set; }
public Decimal Cost2 { get; set; }
}
查看
<table id="tblProducts">
<thead class="text-light bg-dark">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Cost1</th>
<th>Cost2</th>
</tr>
</thead>
<tbody>
@if (Model != null)
{
for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.DisplayFor(m => m[i].first_name)
@Html.HiddenFor(m => m[i].first_name)
</td>
<td>
@Html.DisplayFor(m => m[i].last_name)
@Html.HiddenFor(m => m[i].last_name)
</td>
<td>
@Html.TextBoxFor(m => m[i].Cost1)
@Html.HiddenFor(m => m[i].Cost1)
</td>
<td>
@Html.TextBoxFor(m => m[i].Cost2)
@Html.HiddenFor(m => m[i].Cost2)
</td>
</tr>
}
}
</tbody>
ajax 脚本
<script>
$("#export").click(function (event)
{
var object = @(Html.Raw(Json.Encode(Model)));
$.ajax({
type: 'POST',
url: '/Student/StudentData',
data: JSON.stringify({ modelData: object }),
contentType: 'application/json',
dataType: 'json',
success: function (response)
{
if (response != '')
console.log("Success");
},
failure: function (response)
{
console.log("Failure");
},
error: function (response)
{
console.log("Error:" + response);
}
});
});
</script>
在我的控制器中,Cost1 和 Cost2 都为 0,如何为每列传递新值?
【问题讨论】:
-
我已经添加了一个答案如果你觉得不清楚,请告诉我,我可以让它更简单,并添加一些带有类的服务器端代码用于反序列化。 @Medhani W.
-
谢谢@Ghanat 模型是列表类型
List<StudentDomainModel>我要空了,这是我的控制器[HttpPost] public FileStreamResult StudentData(List<StudentDomainModel> modelData) { } -
不客气,我完全编辑了答案。并添加一个经过测试的控制器层
-
@Ghanat 非常感谢你,非常感谢你的时间,但我的控制器仍然为空,我将
data: { 'formResult': formJsonData },更改为data: JSON.stringify(formJsonData),,但我的控制器仍然为空 -
@Medhaine W. 我的本地解决方案没有任何问题,我已将我的解决方案上传到 github github.com/mghanatabady/MvcTableFromSample
标签: c# asp.net asp.net-mvc asp.net-ajax