在 IEnumerable 方法中传递值

本文关键字:IEnumerable 方法 | 更新日期: 2023-09-27 18:31:30

net mvc c#.我已经创建了视图模型。我可以从表中接收所有行,但是当我尝试在返回列表的方法中传递值时不起作用 这是我的代码
控制器类

public ActionResult Index()
{
    TechnicianDBO db = new TechnicianDBO();
    List<Technician> technicians = db.technicians.ToList();
    return View(technicians);
}
[HttpPost]
public ActionResult Index(int Postcode)
{
    TechnicianDBO db = new TechnicianDBO();
    List<Technician> technicians = db.Jobtechnicians(Postcode).ToList();
    return View(technicians);
}

分贝类

public IEnumerable<Technician> Jobtechnicians(int postcode)
{
    string connectionString = ConfigurationManager.ConnectionStrings["testConnect"].ConnectionString;
    List<Technician> Jobtechnicians = new List<Technician>();
    using (SqlConnection con = new SqlConnection(connectionString))
    {
        SqlCommand cmd = new SqlCommand("spGetTechnicianByPostcode", con);
        con.Open();
        SqlParameter paramId = new SqlParameter();
        paramId.ParameterName = "@postcode";
        paramId.Value = postcode;
        cmd.Parameters.Add(paramId);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            Technician technician = new Technician();
            technician.Id = Convert.ToInt32(dr["techId"]);
            // technician.Username = dr["techUsername"].ToString();
            technician.Firstname = dr["techFirstname"].ToString();
            technician.Lastname = dr["techLastname"].ToString();
            technician.LandlineNo = dr["landlineNo"].ToString();
            technician.MobileNo = dr["mobileNo"].ToString();
            technician.Address1 = dr["address1"].ToString();
            technician.Address2 = dr["address2"].ToString();
            technician.Postcode = Convert.ToInt32(dr["postcode"]);
            technician.Email = dr["email"].ToString();
            technician.Fax = dr["fax"].ToString();
            technician.Profession = Convert.ToInt32(dr["ProfessionId"]);
            Jobtechnicians.Add(technician);
        }
        return Jobtechnicians;
    }
}

在 IEnumerable 方法中传递值

你需要给CommandType

SqlCommand cmd = new SqlCommand("spGetTechnicianByPostcode", con);
cmd.CommandType = CommandType.StoredProcedure;

而且当您调用.ToString()时,您最好检查该列值是否为 null,如果该列允许表中为 null

相关文章: