如何将变量/自定义id值设置为Html.TextBoxFor - MVC,C#,Razor

时间:2017-06-06 20:11:51

标签: c# asp.net-mvc razor

如何为TextBox提供变量ID值?

示例尝试:

 @var variable = model.codeOne;

<div>
@Html.TextBoxFor(item => item.OperationNo, new { id = "@("materialCostInput"+ 
variable)" })
</div>

我在论坛周围寻找这个问题的答案,但还没有找到类似的问题。

2 个答案:

答案 0 :(得分:1)

你可以这样做

@{
    var variable = "123";
 }
@Html.TextBoxFor(item => item.OperationNo, new { id = "materialCostInput" + variable })

答案 1 :(得分:1)

这是一个更完整的答案:

public class SuperModel
{
    public string OperationNo { get; set; }

}

//Create an edmx to your table
public class HomeController : Controller
{
    [HttpPost]
    public ActionResult Index2003(SuperModel sm, FormCollection formCollection)
    {
        var theId = formCollection.Keys[0];
        return View();
    }

    public ActionResult Index2003()
    {
        SuperModel sm = new SuperModel { OperationNo = "op1" };
        return View(sm);
    }

控制器:

@model Testy20161006.Controllers.SuperModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index2003</title>
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            var variable = "456";
            @Html.TextBoxFor(item => item.OperationNo, new { Name = "materialCostInput" + variable })
            <input type="submit" value="submit" />
        }
    </div>
</body>
</html>