如何使用MVC 4制作提交按钮

时间:2014-02-09 13:43:45

标签: asp.net-mvc asp.net-mvc-4

我正在尝试编写一个代码,该代码从用户输入中获取姓氏和名字,并将值存储在带有MVC4的数据表中。我在Accountcontroller.cs下添加了以下代码

将创建一个提交按钮。一旦用户单击提交按钮,它就会将用户输入添加到数据集中。

private void button_Click( object sender, EventArgs e) 

{ 
   SqlConnection cs = new SqlConnection("Data Source = FSCOPEL-PC; ....

   SqlDataAdapter da = new SqlDataAdapter();

   da.insertCommand = new SqlCommand(" INSERT INTO TABLE VALUES ( Firstname, Lastname,  )
}

我还在logincs.html下添加了以下代码,一旦用户登录,就会创建提交按钮。

   <button type="submit" id="btnSave" name="Command" value="Save">Save</button>

2 个答案:

答案 0 :(得分:10)

在MVC中,您必须创建一个表单并将该表单提交给Controller的Action方法。创建表单的语法如下:

查看:

@using (Html.BeginForm("YourActionName", "ControllerName"))
{
    @Html.TextBoxFor(m => m.FirstName)
    @Html.TextBoxFor(m => m.LastName)
    <input type="submit" value="Submit Data" id="btnSubmit" />
}

<强>控制器:

  public ActionResult YourActionName(UserModel model)
       {
          //some operations goes here
          return View(); //return some view to the user
       }

<强>型号:

public class UserModel
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

答案 1 :(得分:0)

 <form method="post">
 //Here you need to add the code for textboxes
 <input type="submit" name="save" value="Save" 
 formaction="@Url.Action("ControllerActionMethodName")" formmethod="post" />
 </form>
 //Afterwards inside the controller you need to decorate the actionmethod 
 with  [httppost] attribute on top of the action method,
 then you will be able to see the submit button functionality working well.

在单击“提交”按钮后添加此代码后,您会注意到调试器点击了操作方法。