在MVC中使用webforms

时间:2013-10-04 10:23:35

标签: asp.net-mvc asp.net-mvc-2 webforms

我正在学习MVC,关注THIS教程。 (链接将直接带你到我被困的地方)。到目前为止,我已经了解到,每个视图都有一个控制器。现在我必须通过教程中提到的Web输入表单从用户那里获取输入。在我的项目中,我有一个名为 Default1 的控制器,我可以将其作为localhost:xyz / Default1 / Index运行。它运行得很完美。

然后我创建了一个名为 Default2 的新Controller,并将其绑定到某个视图以显示一些数据,它完美地用作localhost:xyz / Default2 / Displaycustomer。客户信息是静态的(硬编码)。和控制器是:

    public ViewResult DisplayCustomers()
    {
        Customer cobj = new Customer();
        cobj.Code = "12";
        cobj.Name = "Zeeshan";
        cobj.Amount = 7000;


        return View("DisplayCustomers",cobj);
    }

现在我必须使用教程中提到的 html page ,从用户那里获取关于cutomer iformation的输入。所以我尝试在查看文件夹下添加新的 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 / entryform等但失败了。 (在我的entryform.aspx中,我提到了表单 action =“DisplayCustomer”

2 个答案:

答案 0 :(得分:1)

听起来你错过的只是显示表单的动作。换句话说,您只需要一个动作来显示表单。该表单的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">

然后,您将使用网址http://test.server/Customer/New访问您的表单。

答案 1 :(得分:0)

这可能不是世界上最好的例子......但这至少会让你滚动......

url将是: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>