将数据从数据库发送到文本框asp.net mvc

时间:2016-05-24 17:39:16

标签: html asp.net-mvc textbox

单击“搜索”按钮时,如何正确显示数据库到文本框的数据?它应显示项目名称和该产品代码的价格

enter image description here

控制器

public ActionResult Index(string searchString)
{
    using(MyDatabaseEntities db = new MyDatabaseEntities())
    {
        var products = from s in db.Products
                       select s;
        if (!String.IsNullOrEmpty(searchString))
        {
            products = products.Where(s => s.ProductCode.Equals(searchString));
        }
        return View(products.ToList());
    }
}

索引

<div class="form-group">
    <table style="text-align:left; margin-bottom:10px;">
        <tr>
            <td>Item Code</td>
            <td>@Html.TextBox("SearchString")
        </td>
        <tr style="background-color:lightgray;">
            <td colspan="2"></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" class="btn btn-block btn-info"id="buttonsearch" value="Search" />
            </td>
        </tr>
        <tr>
            <td>&nbsp;</td>
        </tr>  
        @foreach (var item in Model) { 
            <tr>
                <td style="text-align:left;">Item Name</td
                <td>@Html.DisplayFor(modelItem=> item.ProductName)</td>
            </tr>
            <tr>
                <td>Unit Price</td>
                <td style="text-align:right;">@Html.DisplayFor(modelItem => item.Price)</td>
            </tr>
        }
        <tr>
            <td style="text-align:left;">Quantity</td>
            <td>
                <input type="text" id="quantity" class="input-sm" />
                <span class="error">Product Name  required</span>
            </td>
        </tr>
        <tr>
            <td style="text-align:left;">Discount</td>
            <td>
                <input type="text" id="discount" class="input-sm" style="text-align:right;" placeholder="0.00" />
                <span class="error">Product Name required</span>
            </td>
        </tr>
    </table>
</div>

1 个答案:

答案 0 :(得分:0)

而不是.ToList()使用.FirstOrDefault();以防你想在文本框中填充一条记录。