如何在单击按钮后从MVC 4视图中将文本框值保存到SQL?

时间:2014-03-28 10:53:25

标签: c# sql asp.net-mvc-4

我在SQL中有一个Log表。

ID   UserName  VisitedTime  VisitedUrl IpAdress Browser

当前用户访问任意页面时,我可以保存UserName,VisitedTime,VisitedUrl,IpAdress,浏览器。

控制器

public ActionResult Index(string date1, string date2, string txt)


    {
        string browser = Request.Browser.Browser;
        string IP = HttpContext.Request.UserHostAddress;
        string userName = HttpContext.User.Identity.Name.ToString();
        string url = Request.Url.AbsoluteUri.ToString();
        mydataclass newDataclass=new mydataclass ();
        string sql = @"Insert Into Loglar (UserName,VisitedTime,VisitedUrl,IpAdress,Browser ) values 
           ('" + userName.ToString() + "','" + DateTime.Now.ToString() + "','"
               + url+ "','" + IP+ "','" + browser+ "')";

        newDataclass.DataCenterDoSql(sql);
}

 public class mydataclass 
  {

 public mydataclass () { }  
 public bool DataCenterDoSql(string sql)
    {
        SqlConnection con = new SqlConnection();

      try
        {
       con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
       con.Open();
     }
        catch
        {
        }

        SqlCommand cmd = new SqlCommand();
        try
        {
            cmd.Connection = con;
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
        finally
        {
            con.Close();
        }
        return true;
    }


  }

它正在工作。没有任何问题。

我在ViewPartial上有两个DateEdit,一个按钮,一个文本框和一个网格。 当我选择两个日期时,输入字符串到文本框并单击按钮,某些内容的结果可以显示在gridview上。

我的问题:如何在点击按钮后将DateEdit 1,DateEdit 2和TextBox值保存到我的新表中。

新表

    ID   UserName  VisitedTime  VisitedUrl IpAdress  Browser  Date1 Date2 TextBox

1 个答案:

答案 0 :(得分:1)

一种方法是使用Ajax过滤数据。其他方式如下:

在行动中采取这些价值观:

public ActionResult Index(string date1, string date2, string txt)
{
   ViewBag.Date1 = date1;
   ViewBag.Date2 = date2;
   ViewBag.Txt = txt;
   ....
   //your code
}

并且在视野中:

@{
   string date1Value = string.Empty;
   string date2Value = string.Empty;
   string txtValue= string.Empty;

   if(ViewBag.Date1 != null) { date1Value = (string)ViewBag.Date1;  }
   if(ViewBag.Date2 != null) { date2Value = (string)ViewBag.Date2;  }
   if(ViewBag.Txt!= null) { txtValue= (string)ViewBag.Txt;  }
}

//...
<input name="date1" value="@date1Value "  />
<input name="date2" value="@date2Value "  />
<input name="txt" value="@txtValue"  />
//...