我想使用输入标记过滤我的表,如:“SELECT * FROM tblaccount WHERE accountNo ='document.getElementById('txtSearch')。value “”将输入标记的ASP.NET MVC值转换为sql查询
这是我AccountsViewModel
namespace MyProject.Models
{
public class AccountsViewModel
{
public DataTable Accounts { get; set; }
}
}
SelectModel.cs
namespace MyProject.Models
{
public class SelectModel
{
private static SqlConnection GetCn()
{
SqlConnection cn = new SqlConnection(@"MyConnectionString");
return cn;
}
public DataSet GetAccounts()
{
SqlConnection cn = GetCn();
SqlCommand cmd = new SqlCommand("SELECT * FROM tblaccount ORDER BY accountNo ASC", cn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
}
}
HomeController.cs
namespace MyProject.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(MyProject.Models.SelectModel selectmodel)
{
AccountViewModel vm = new AccountViewModel();
DataSet ds = selectmodel.GetAccounts();
vm.Accounts = ds.Tables[0];
return View(vm);
}
}
}
Index.chtml
@model MyProject.Models.AccountsViewModel
<label for="txtSearch">Search: </label>
<input type="text" class="form-control" id="txtSearch">
<button class="btn btn-default" type="submit" id="btnSearch">Search</button>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th">Account Number</th>
<th">Transaction Date</th>
</tr>
</thead>
<tbody>
@foreach (System.Data.DataRow dr in Model.Accounts.Rows)
{
<tr>
<td>@dr["Id"].ToString()</td>
<td>@dr["accountNo"].ToString()</td>
<td>@dr["dateTrans"].ToString()</td>
</tr>}
</tbody>
</table>
更新:忘了补充上查看Index.chtml – Hanzou