根据文本框输入显示图像

Display images based on Textbox input

我想根据 TextBox 输入在我的视图中显示多个图像。

我有这个Controller:

public ActionResult GetProducts(long id, Search obj)
{
    GetSearchByDropdowns();
    using (ThBEntities1 db = new ThBEntities1())
    {
        if (id == null) {
            return View("Index");
        }

        byte[] image = db.Searches.Where(x => x.SearchTextBox == x.Product).SingleOrDefault().producturl;
        var stream = new MemoryStream(image.ToArray());
        return new FileStreamResult(stream, "image/jpeg");
    }
    return View("~/Views/Search/Index.cshtml", obj);
}

在我看来

if (Model.producturl != null)
{
    for (int i = 0; i < 6; i++)--I only have 6 records
    {
        <img src='@Url.Action("GetProducts", "Search", new{ id = i })' />
    }
}

还有我的模特

public partial class Search
{
    public long ID { get; set; }
    public string Product { get; set; }
    public byte[] producturl { get; set; }
}

我收到此错误:

    The parameters dictionary contains a null entry for parameter 'id' of
non-nullable type 'System.Int64' for method
'System.Web.Mvc.ActionResult GetProducts(Int64, ThunderBird.Search)'
in 'ThunderBird.Controllers.SearchController'. An optional parameter
 must be a reference type, a nullable type, or be declared as an
 optional parameter.

我知道它来自 GetProducts(long id, Search obj) ,但我怎样才能将视图中的模型作为参数传递?

我相信如果你是通过这种方式创建 img 的 src

<img src='@Url.Action("GetProducts", "Search", new{ id = i })' />

你不能看到参数字典的这个错误,否则你的图像将不会在浏览器上呈现。

我认为您是从按钮或表单等其他来源点击此方法的。

其实我是这样做的:

Controller
      public ActionResult GetProducts(Search obj)
            {
                GetSearchByDropdowns();

                Search c = null;
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = "Data Source=DESKTOP-QR66UQL;Initial Catalog=ThB;Integrated Security=True";
                conn.Open();
                using (conn)
                {
                    SqlCommand cmd = new SqlCommand("Select ProductImage from Search where Product='" + obj.SearchTextBox + "'");
                    cmd.Connection = conn;
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        c = new Search();
                        c.ImagePath = reader["ProductImage"].ToString();
                        obj.S.Add(c);
                    }
                    return View("~/Views/Search/Index.cshtml", obj);
                }
            }

View
 if (Model.S != null)
    {
        foreach (var item in Model.S)
        {
            <img src='@Url.Content(Model.ImagePath)' alt="Image" />
        }
    }

Mybe 不是理想的解决方案,但它符合我的预期。