RAZOR SQL。使用所选文本中的值并将该变量添加到下一个查询中

时间:2014-01-28 20:36:07

标签: c# asp.net sql razor

我正在尝试从列表框中获取所选文本的值:

    var db = Database.Open("localdb");
    var listRegion = "SELECT NameRegion,IdRegion FROM OfficesRegions ORDER BY NameRegion";

    List<SelectListItem> Regiondropdownlistdata = new List<SelectListItem>();
    bool isSelected = false;
    foreach (var item in db.Query(listRegion)){
    Regiondropdownlistdata.Add(new SelectListItem 
    {
        Value = item.IdRegion.ToString(),
        Text = item.NameRegion,
        Selected = isSelected
    });
    }
Regiondropdownlistdata.Add(new SelectListItem {Text = "Select Region",Value = "0", Selected = true });

并将该值添加到我的查询中以自动提取相关商店:

    var listoffice = "SELECT OfficeName,IdRegion FROM Offices WHERE IdRegion = @0 ORDER BY OfficeName";

List<SelectListItem> Officedropdownlistdata = new List<SelectListItem>();
bool selected = true;
foreach (var office in db.Query(listoffice)){
    Officedropdownlistdata.Add(new SelectListItem
    {
        Value = office.IdRegion.ToString(),
        Text = office.OfficeName,
        Selected = selected
    });
}

我是新手,所以非常感谢任何帮助。 谢谢!

1 个答案:

答案 0 :(得分:0)

BAD 因为它对sql注入是开放的

String.Format("SELECT OfficeName,IdRegion FROM Offices WHERE IdRegion = {0} ORDER BY OfficeName", SomeStringVlaue);

<强>更好

 string esqlQuery =
    @"SELECT OfficeName,IdRegion FROM Offices WHERE IdRegion = @Target ORDER BY OfficeName";

    using (EntityCommand cmd = new EntityCommand(esqlQuery, conn))
    {
    // Create two parameters and add them to
    // the EntityCommand's Parameters collection
    EntityParameter param1 = new EntityParameter();
    param1.ParameterName = "target";
    param1.Value = "Cool Parameters";

    cmd.Parameters.Add(param1);
    .....


     Parameterized EF Queries