【问题标题】:How to save textbox value to SQL from MVC 4 view after click button?单击按钮后如何将文本框值从 MVC 4 视图保存到 SQL?
【发布时间】:2014-03-28 10:53:24
【问题描述】:

我在 SQL 中有一个日志表。

表格

ID   UserName  VisitedTime  VisitedUrl IpAdress Browser

当当前用户访问任何页面时,我可以保存 UserName、VisitedTime、VisitedUrl、IpAdress、Browser。

控制器

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

【问题讨论】:

  • 您可以按照与第一张桌子相同的方式进行操作。
  • 我不知道如何从控制器访问视图。

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


【解决方案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"  />
//...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多