【发布时间】:2013-09-11 04:15:04
【问题描述】:
这是我的强类型视图
@using ( Html.BeginForm("Index", "Home",null, FormMethod.Post, new { id="FormPost" }))
{
@Html.TextBoxFor(x => x.Name) @Html.ValidationMessageFor(x => x.Name)
<br />
@Html.TextBoxFor(x => x.LastName) @Html.ValidationMessageFor(x => x.LastName)
<br />
@Html.TextBoxFor(x => x.Age) @Html.ValidationMessageFor(x => x.Age)
<br />
<input type=submit value="submit" />
<br /><br />
}
这是视图模型类:
public class MyViewModel
{
[Required(ErrorMessage="Please enter first name") ]
public string Name { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
}
我使用下面的脚本将表单发布回索引操作方法
ReusableJqueryPost.prototype.CommonPost = function (formId) {
var fid = $("#" + formId);
var validated = $(fid).valid();
if (validated) {
$.ajax({
type: 'POST',
url: $(fid).attr('action'),
data: $(fid).serialize(),
accept: 'application/json',
error: function (xhr, status, error) {
alert('error: ' + xhr.responseText + '-' + error);
},
success: function (response) {
alert('DATA SAVED!');
var resp = response;
}
});
}
};
Index Action 方法现在可以返回为 ActionResult
return View(objMyViewModel);
or as or JsonResult
return Json(objMyViewModel);
如果我 不 使用 jquery 帖子并将数据作为 ActionResult 返回,那么我不需要在客户端做任何事情.由于@Html.TextBoxFor(....)
由于我使用 jquery post 发布到 action 方法并将数据返回为 JsonResult ,我希望将 json 字符串中的每个元素自动绑定到相应的 Html.TextBoxFor(...)文本框,而不必使用 jquery 来查找文本框或选择框(如果有的话),然后根据 json 字符串中接收到的值将数据绑定到它。
问题
- 开箱即用的 asp.net mvc 的某些功能是否可以实现这一点?
- 这是唯一可用的选项,可以使用 jquery 按名称/id 查找文本框或下拉菜单或任何其他输入元素,然后从 json 字符串中分配值
- 有什么方法可以让我写一次这个作业,这样我就可以重复使用相同的代码,而无需在整个项目中为每个视图重复它?就像我在这里有一个 jquery post 方法可以在整个项目中使用一样。
谢谢
【问题讨论】:
标签: asp.net asp.net-mvc jquery