Skip to main content
 首页 » 编程设计

c#之在 MVC 中使用 HTML 按钮

2024年02月24日29shanyou

我觉得问这个问题有点愚蠢,但我只想知道如何让 html 按钮在我的 Controller 上调用服务器站点操作。

例如,假设我有一个文本区域和一个提交按钮。这个想法是单击提交按钮,文本区域中的文本将被提交到数据库。非常简单的东西。

谢谢你的帮助!

请您参考如下方法:

在 aspx 中:

     <%Html.BeginForm("Hello","Home",FormMethod.Post);%> <!--Name of method, name of controller, formmethod --> 
        <input type="text" id="userName" maxlength="50" name="userName"/> 
        <input id="Submit1" type="submit" value="Say Hello!" /> 
     <%Html.EndForm();%> 
     <h2><%= Html.Encode(TempData["Message"]) %></h2> 

在 Controller 中(本例中为 HomeController):

public ViewResult Hello(string userName) //note this variable is exactly what is the name of text input on page 
        { 
            //simple example, take input and pass back out 
            TempData["Message"] = "Hello, " + userName; 
            return View("Index",TempData); 
        } 

编辑:解决有关维护 URL 的其他问题

就您的 URL 而言,实现“原地不动”的一种方法是“重载” Controller 的 Index 方法,如下所示

[AcceptVerbs(HttpVerbs.Post)] //This is KEY <----- 
        public ActionResult Index(string userName) 
        { 
            //simple example, take input and pass back out 
            TempData["Message"] = "Hello, " + userName; 
            return View("Index",TempData); 
        } 

然后在您的 Index.aspx 中更改 Html.Begin 表单,如下所示,您现在只需指向默认操作

<%Html.BeginForm("Index","Home",FormMethod.Post);%>  

由于您正在发布到 Controller 并且没有获取(默认索引操作)设置为 AcceptVerb POST 并采用用户名字符串的版本将运行并且您的 URL 应该被维护