2015-02-10 48 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