我正在学习MVC,下面是这教程。(链接将直接带你到我被困的地方)。到目前为止,我已经了解到,每个视图都有一个控制器。现在,我必须采取从用户通过网站输入表格,如教程中提到的输入。在我的项目中,我有一个名为Default1的控制器,我可以作为localhost运行它:xyz/Default1 1/Index。它运行得很完美。
然后,我创建了一个名为Default2的新控制器,并将它绑定到某个视图以显示某些数据,它作为本地主机运行得非常完美:xyz/Default2 2/Displaycustomer。客户信息是静态的(硬编码)。主计长如下:
public ViewResult DisplayCustomers()
{
Customer cobj = new Customer();
cobj.Code = "12";
cobj.Name = "Zeeshan";
cobj.Amount = 7000;
return View("DisplayCustomers",cobj);
}现在,我必须接受用户的输入,关于cutomer信息,使用教程中提到的html页面。因此,我尝试在视图文件夹下添加一个新的webform,并将控制器修改为:
[HttpPost]
public ViewResult DisplayCustomers()
{
Customer cobj = new Customer();
cobj.Code = Request.Form["Id"].ToString();
cobj.Name = Request.Form["Name"].ToString();
cobj.Amount = Convert.ToDouble(Request.Form["Amount"].ToString());
return View("DisplayCustomers",cobj);
}我的问题是:我如何使我的项目开始工作,以便它首先接受输入,然后显示它,使用上面的控制器?我在正确的位置添加网页了吗?运行它的链接是什么?我尝试了localhost:xyz/Default2 2/entryform等,但是失败了。(在我的action="DisplayCustomer"中,我提到了表单entryform.aspx )
发布于 2013-10-04 13:55:23
听起来你缺少的是一个只显示表单的动作。换句话说,你只需要一个动作来显示一个表单。该表单的POST操作应该引用控制器的DisplayCustomers操作。
所以在你的控制器代码中:
public class CustomerController : Controller
{
[HttpGet]
public ViewResult New()
{
return View("NewCustomer"); //Our view that contains the new customer form.
}
// Add your code for displaying customers below
}在你看来,你有这样的代码
@using(Html.BeginForm("DisplayCustomers", "Customer")) {
<!-- Add your form controls here -->
}注意,我使用的是BeginForm助手的版本,它指定要调用的动作方法和控制器。这将编写form标记以回发到您的DisplayCustomers操作。以下是等效的HTML:
<form method="POST" action="/Customer/DisplayCustomers">然后使用URL http://test.server/Customer/New访问表单。
发布于 2013-10-04 13:37:25
这可能不是world...but中最好的例子,这至少会让你滚开。
网址是:localhost:1234/Home/Customer
控制器
public ActionResult Customer()
{
return View();
}
[HttpPost]
public ActionResult Customer(FormCollection frm)
{
var name = frm["name"].ToString();
var address = frm["address"].ToString();
ViewBag.Name = name;
ViewBag.Address = address;
return View();
}观景
<div>
@using (Html.BeginForm())
{
<input type="text" name="name" id="name" />
<input type="text" name="address" id="address"/>
<input type="submit" name="submit" value="submit" />
<input type="text" name="namedisplay" value='@ViewBag.Name'/>
<input type="text" name="addressdisplay" value='@ViewBag.Address'/>
}
</div>https://stackoverflow.com/questions/19178929
复制相似问题