我刚刚开始学习 ASP.NET MVC 中的 ViewModel。所以,我想实现一个示例如下:
商业实体
public class AddModel
{
public int a { get; set; }
public int b { get; set; }
public int Add()
{
return (this.a + this.b);
}
}
添加 View 模型
public class AddViewModel
{
public AddModel addModel;
public int Total { get; set; }
}
Controller
public class AddController : Controller
{
[HttpPost]
public JsonResult Add(AddViewModel model)
{
int iSum = model.addModel.a + model.addModel.b;
model.Total = iSum;
return Json(model);
}
public ActionResult Index()
{
return View();
}
}
查看实现
@model ViewModelApplication.AddViewModel
<script type="text/javascript" src="../../Scripts/MicrosoftAjax.js"></script>
<script src="../../Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
<script type="text/javascript">
function Callback(data) {
alert("I am sucess call");
}
function Failed() {
alert("I am a failure call");
}
</script>
@using (Ajax.BeginForm("Add", "Add", new AjaxOptions { OnSuccess = "Callback", OnFailure = "Failed" }))
{
<table align="center">
<tr>
<td class="tdCol1Align">
<label>
Number1</label>
</td>
<td class="tdCol2Align">
@Html.TextBoxFor(Model => Model.addModel.a)
</td>
</tr>
<tr>
<td class="tdCol1Align">
<label>
Number2</label>
</td>
<td class="tdCol2Align">
@Html.TextBoxFor(Model => Model.addModel.b)
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Add" class="button" />
</td>
</tr>
</table>
}
这里的问题是,每当单击 Add
按钮时,我都无法检索输入到文本框中的值;相应的 AJAX 操作就是它。
当我尝试访问 a
和 b
的值时,我得到的是空值,而不是输入到文本框中的值。
我不确定我哪里出错了。请帮忙。
最佳答案
你的 View 模型应该是这样的
public class AddViewModel
{
public int a { get; set; }
public int b { get; set; }
public int Total { get; set; }
}
在 cshtml 中
<td class="tdCol2Align">
@Html.TextBoxFor(m=> m.a)
</td>
<td class="tdCol2Align">
@Html.TextBoxFor(m=> m.b)
</td>
在 Controller 中
[HttpPost]
public JsonResult Add(AddViewModel model)
{
int iSum = model.a + model.b;
model.Total = iSum;
return Json(model);
}
编辑
View 模型用于呈现您的 View ,不要在其中放置任何逻辑。如果您有更复杂的模型,那么将很难将 Model
映射到 ViewModel
。为此,您可以使用 AutoMapper 或 ValueInjector 在模型和 View 模型之间进行映射。
自动映射器链接 http://automapper.codeplex.com/
值(value)注入(inject)器链接 http://valueinjecter.codeplex.com/
希望对你有帮助
关于c# - 如何在 ASP.NET MVC 中使用 ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20323713/