2

所以我试图在单击时有一个按钮,它将数据发送到 sql 服务器。我想我可以创建一个只有一个提交按钮的表单,然后我会在我的家庭控制器中处理那个提交按钮。

我的html是这样的:

<body>
<div  style="border: solid; max-width: 300px; margin-left: auto; margin-right: auto">


    @using(Html.BeginForm())
    {

    <input type="submit" value="Vote"/>
    }

</div>



</body>

在我的家庭控制器中,我认为它应该处理以下形式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;

namespace WAgermanClub.Controllers
{
public class HomeController : Controller
{


[HttpPost]
    public ActionResult add(string vote1)
    {




        SqlConnection vote1connection = new SqlConnection("user id=userid;" +
                               "password=validpassword;server=o5z5dpwpzi.database.windows.net;" +
                               "Trusted_Connection=yes;" +
                               "database=wagermanclub_votes; " +
                               "connection timeout=30");
        try
        {
            vote1connection.Open();
        }
        catch (Exception g)
        {
            Console.WriteLine(g.ToString());
        }

        try
        {
            SqlDataReader myReader = null;
            SqlCommand myCommand = new SqlCommand("select * from table", vote1connection);
            myReader = myCommand.ExecuteReader();
            while (myReader.Read())
            {

                Console.WriteLine(myReader["Vote1"].ToString());
            }
        }
        catch (Exception i)
        {
            Console.WriteLine(i.ToString());
        }


        SqlCommand vote1command = new SqlCommand("INSERT INTO table (Column1, Vote1) " +
                              "Values (1, 'Vote1' + 1)", vote1connection);


        vote1command.ExecuteNonQuery();

        try
        {
            vote1connection.Close();
        }
        catch (Exception h)
        {
            Console.WriteLine(h.ToString());
        }






    }
}
}

一切看起来都很好,除了我收到一条错误消息,指出在 add(string vote1) 中并非所有代码路径都返回一个值。我究竟做错了什么?我对 html 表单没有那么大的把握,但我觉得一旦我掌握了这一点,它将导致更好的理解。

所有帮助表示赞赏!谢谢!

4

1 回答 1

3

这个;

public ActionResult add(string vote1)

意味着您已经声明了一个返回 ActionResult 变量的方法。您的方法中没有 return 语句。解决此问题后,错误将消失。

于 2013-09-10T00:25:49.467 回答