简体   繁体   中英

how to set variable/custom id value to Html.TextBoxFor - MVC, C#, Razor

How does one give a TextBoxFor a variable ID value?

Example Attempt:

 @var variable = model.codeOne;

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

I have looked around the forum for an answer to this question, but have yet to find a similar question.

You can do like this

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

This is a more complete answer:

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);
    }

Controller:

@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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM