如何从TextBox中获取输入并在MVC中显示在视图中
问题描述:
我想显示一个TextBox
。因为如果放弃任何输入的字符串和按钮点击它应该让喜欢本如何从TextBox中获取输入并在MVC中显示在视图中
海,什么是乌拉圭回合的名字
[文本框]
欢迎,乌尔名称是“XYZ”
我新的MVC
。请帮助我做到这一点。
查看
@{
ViewBag.Title = "MyPage";
}
<h2>Mymethod</h2>
<h3>@ViewBag.Message</h3>
@Html.TextBox("Name")
<form method="post">
<input type="submit" value="Submit" name="btn" />
</form>
HomeController.cs
public ActionResult Mymethod()
{
ViewBag.Message = "Hello what is ur name ??? ";
return View();
}
答
有很多方法可以完成你想要的。我会为您提供一个简单的方法,请修改并更改它以符合您的方案。
我通常会推荐使用高于任何其他方式的视图模型,例如使用single
字符串值或使用FormCollection
或或ViewBag
。他们可以工作,但我更喜欢使用视图模型。
我回答的是,他们应该有什么视图模型做什么的问题时,请阅读:
首先您将创建一个可以处理你的输入数据,如第一视图模型姓名,姓氏,年龄等。然后,您将通过此视图模型进入视图。在你的榜样,我将只包括名称:
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
的许多在线教程。
答
修改当前视图以
@using(Html.BeginForm("ControllerName","Mymethod",FormMethod.Post))
{
<input type="submit" value="Submit" name="btn" />
}
在控制器中添加另一种操作方法是这样的:
[HttpPost]
public ActionResult Mymethod(FormCollection form)
{
string Name = form["Name"];
Viewbag.Name = Name;
return View()
}
然后添加视图到这个控制器并写入它。
Hi , Your Name is @Viewbag.Name
答
您应该将您的表格包装在form
标记中。毕竟这是一个form
。所以当你点击提交时,你提交的是form
。
<form method="post">
<h2>Mymethod</h2>
<h3>@ViewBag.Message</h3>
@Html.TextBox("Name")
@if (!String.IsNullOrEmpty(ViewBag.Name))
{
<h3>
welcome,ur name is @ViewBag.Name
</h3>
}
<input type="submit" value="Submit" name="btn" />
</form>
在控制器上,你需要添加HttpPost
处理您Mymethod
行动。这是您的Web服务器接受您提交的form
的地方。
[HttpPost]
public ActionResult Mymethod(string name)
{
ViewBag.Message = "Hello what is ur name ???";
ViewBag.Name = name;
return View();
}
有很多不错的MVC教程视频,我建议你去微软虚拟学院或Youtube,你一定会找到你需要的。 –