2015-02-10 86 views
0

在我的应用程序中有两个文本框和一个按钮,当用户单击按钮时,我想让文本到控制器。HttpPost没有在ASP.net中被触发MVC

我试图HttpPost,但它不工作,这是我的代码:

查看

@model examplemvc1.Models.sample 
@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

@Html.TextBoxFor(a=>a.username) 
@Html.TextBoxFor(a=>a.password) 
<input type="submit" value"button1" /> 

控制器

namespace examplemvc1.Controllers 
{ 
    public class sampleController : Controller 
    { 
     // 
     // GET: /sample/ 
     [HttpGet] 
     public ActionResult Index() 
     { 
      return View(); 
     } 
     [HttpPost] 
     public ActionResult Index(sample sam) 
     { 
      return View(sam); 
     } 
    } 
} 

模式

namespace examplemvc1.Models 
{ 
    public class sample 
    { 
     public string username { get; set; } 
     public string password { get; set; } 
    } 
} 
+1

表单在哪里? – Tushar 2015-02-10 10:37:50

+0

您的'TextBoxFor'控件和提交按钮需要位于表单标签内。使用@using(Html.BeginForm())'。没有这个,你不能POST到控制器方法。 – markpsmith 2015-02-10 10:39:40

+0

@TusharGupta我是编程新手请帮助我,如果我的代码是错误的 – 2015-02-10 10:40:03

回答

1

在OP的要求:

@model examplemvc1.Models.sample 
@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 
@using (Html.BeginForm()) 
{ 
    @Html.TextBoxFor(a=>a.username) 
    @Html.TextBoxFor(a=>a.password) 

    <input type="submit" value"button1" /> 
} 
2

您必须添加将被张贴到你的控制器形式

@using (Html.BeginForm()) 
{ 
    @Html.TextBox("Name"); 
    @Html.Password("Password"); 
    <input type="submit" value="Sign In"> 
} 

产生如下的表单元素

<form action="/Original Controller/Original Action" action="post">

+0

多么令人难以置信的粗鲁! – markpsmith 2015-02-10 10:44:36

+0

我在写回答的同时没有问题交配,我应该删除它吗? – Tushar 2015-02-10 10:45:45

+0

我不是你的伴侣。 – markpsmith 2015-02-10 10:46:10