【问题标题】:How to make a submit button with MVC 4如何使用 MVC 4 制作提交按钮
【发布时间】:2014-02-09 13:43:45
【问题描述】:

我正在尝试编写一个代码,该代码从用户输入中获取姓氏和名字,并将值存储在 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>

【问题讨论】:

  • 您似乎尝试将 ASP.NET WebForms 与 ASP.NET MVC 结合使用...
  • 这不是 MVC 的工作方式。要完成您想要的,您要么需要进行回发并以这种方式保存用户,要么进行 ajax 调用。在这里查看我的答案stackoverflow.com/questions/19643864/… 了解如何做到这一点

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


【解决方案1】:

在 MVC 中,您必须创建一个表单并将该表单提交给控制器的 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; }
}

【讨论】:

  • 本示例中不需要声明id="btnSubmit",对吗?
  • 这是示例代码,id用于一些jquery函数。
【解决方案2】:
 <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.

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

【讨论】:

    猜你喜欢
    • 2015-04-08
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2017-10-24
    • 2011-05-10
    相关资源
    最近更新 更多