有很多方法可以完成你想要的。我会为您提供一个简单的方法,请修改并更改它以符合您的方案。
我通常会推荐使用高于任何其他方式的视图模型,例如使用single
字符串值或使用FormCollection
或或ViewBag
。他们可以工作,但我更喜欢使用视图模型。
我回答的是,他们应该有什么视图模型做什么的问题时,请阅读:
What is ViewModel in MVC?
首先您将创建一个可以处理你的输入数据,如第一视图模型姓名,姓氏,年龄等。然后,您将通过此视图模型进入视图。在你的榜样,我将只包括名称:
public class ViewModel
{
public string Name { get; set; }
}
在你Create
操作方法,你将会实例化视图模型,并把它传递给视图。当你点击按钮提交表单,则POST操作方法将收到此视图模型作为输入参数:
public ActionResult Create()
{
ViewModel model = new ViewModel();
return View(model);
}
[HttpPost]
public ActionResult Create(ViewModel model)
{
if (!ModelState.IsValid)
{
// If validation fails send the view model back to the view and fix any errors
return View(model);
}
// Do what you need to do here if there are no validation errors
// In your example we are posting back to the current view to
// display the welcome message
return View(model);
}
然后最后你看到会是这样的:
@model Project.Models.ViewModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(m => m.Name)
<button type="submit">Submit</button>
if (!string.IsNullOrWhiteSpace(Model.Name))
{
<p>welcome, your name is @Model.Name</p>
}
}
请花一些时间阅读关于ASP.NET MVC
的许多在线教程。
有很多不错的MVC教程视频,我建议你去微软虚拟学院或Youtube,你一定会找到你需要的。 –