使用MVC和jQuery动态&安培;一贯值添加到表 [英] Using MVC and JQuery to dynamically & consistently add values to a table
问题描述
我可以在它有多个值的表格。
I have a form which can have multiple values in it.
例如:
请列出您的家属。
我有一个包含我的三个字段一个字段
I have a fieldset containing my three fields
- 名字,
- 姓
- 出生日期
以及一个Add按钮。
在成功的jQuery的Ajax请求和我的添加按钮火灾增加了一个表行插入表
My add button fires of a jQuery ajax request and upon the success adds a table row into the table
伪code:
$.ajax({
url: myUrl,
data: myData,
success: function(){
var row = $("<tr id='...'>");
row.append("<td>").text(txtFirstName.val());
row.append("<td>").text(txtLastName.val());
row.append("<td>").text(dteDateOfBirth.val());
row.appendTo($("#myDependantsTable"));
}
...
});
这个伟大的工程。不过,我现在已经在两个不同的地方定义我的HTML,我的javascript并以我观
This works great. However, now I have my HTML defined in two different places, my javascript and also in my View
IE:
<tr>
<td>@Model.FirstName</td>
<td>@Model.LastName</td>
<td>@Model.DateOfBirth</td>
</tr>
一个问题进场时,我开始修改这些,比如,日期列添加类,我需要修改code两次。
A problem comes into play when I start modifying these, such as, adding a class on the date column, I need to modify the code twice.
反正是有解决这个问题?
Is there anyway around this problem?
我想:
- 行无以复加ajaxy不回发
- 一致的布局,我只需要做出改变在一个地方
推荐答案
您可以有一个调用Ajax请求返回一个包含一行的局部视图控制器动作。同样的部分生成的表时,你会使用。因此,而不是操纵与JavaScript的HTML,只需追加返回部分表:
You could have the controller action that is called with AJAX request to return a partial view containing a row. The same partial you would use when generating your table. So instead of manipulating HTML with javascript, simply append the returned partial to the table:
$.ajax({
url: myUrl,
data: {
// That's to bind to the view model that the controller
// action you are invoking with the AJAX request takes
// as parameter
firstName: txtFirstName.val(),
lastName: txtLastName.val(),
dob: dteDateOfBirth.val()
}
success: function(result) {
$("#myDependantsTable").append(result);
}
...
});
和在你的标记:
<table id="myDependantsTable">
@foreach(var item in Model)
{
@Html.Partial("_Row", item)
}
</table>
现在你的控制器操作将返回相同的部分:
Now your controller action will return the same partial:
public ActionResult SomeActionInvokedWithAjax(MyViewModel model)
{
return PartialView("_Row", model);
}
这篇关于使用MVC和jQuery动态&安培;一贯值添加到表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!