【发布时间】:2019-11-28 14:20:52
【问题描述】:
我有一个基本的搜索框,我想在用户按下提交/单击回车键时显示数据。单击时会显示 div,但即使我可以单步执行数据访问代码并查看数据正在添加到列表中,数据也会返回 null。谁能帮我解决这个问题?
我已经尝试了多种方法来完成这项工作。我相信我的问题出在 Homecontroller 以及 View 的显示方式上。
SearchViewModel.cs
public class SearchViewModel
{
[DisplayName("Search Query *")]
[Required]
public string Query { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
DataAccess.cs
public static bool GetSearchData(string searchString, out List<SearchViewModel> lstModel)
{
lstModel = new List<SearchViewModel>();
try
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "select Subject, Body from TABLE where Subject = @subject ";
command.Parameters.AddWithValue("@subject", searchString);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
SearchViewModel model = new SearchViewModel();
model.Subject = reader.GetValue(0).ToString();
model.Body = reader.GetValue(1).ToString();
lstModel.Add(model);
}
connection.Close();
return true;
}
catch (Exception exc)
{
exc.ToString();
return false;
}
}
HomeController.cs
List<SearchViewModel> lstModel = new List<SearchViewModel>();
public ActionResult Index(SearchViewModel model)
{
if (!ModelState.IsValid)
{
// There was a validation error => redisplay the view so
// that the user can fix it
return View(model);
}
else
{
string searchString = model.Query;
DataAccess.GetSearchData(searchString, out lstModel);
return View(model);
}
}
Index.cs(主视图)
@using (Html.BeginForm())
{
@Html.LabelFor(x => Model.Query)
@Html.EditorFor(x => x.Query)
@Html.ValidationMessageFor(x => x.Query)
<button type="submit">Search</button>
}
@if (Model.Query != null)
{
<div class="results-panel" style="display:block;" )">
<h4 class="card-title">@Model.Subject</h4>
@Model.Body
</div>
}
searchString 被传递给 DataAccess 函数,它正在用数据填充对象,当我在 Home Index 视图中调试它时它显示为 null。任何人都可以帮忙吗?我相信我非常接近。
【问题讨论】:
-
哎呀,不要使用
.GetValue(0)从特定列中获取值!如果列顺序发生变化,它将中断。明确并按名称引用列。或者更好的是,使用Dapper 将数据库结果直接映射到强类型对象。 -
为什么要使用序数?使用
GetFieldValue<T>("columnname")。 -
我得到了它的工作并将发布解决方案。
标签: c# asp.net .net asp.net-core razor