简体   繁体   中英

In ASP.NET MVC 4 Razor, how do you get the value (text) of @Html.Label?

I'm sorry I've tried searching but I didnt receive any information related to my problem.

My view:

<legend>COMFIRM</legend>
    @using (Ajax.BeginForm("AdminDeleteResult", "Admin",
                            new AjaxOptions { UpdateTargetId = "div" }))
    {
        <div id="div"></div>
        <h6>ARE YOU SURE WANT TO DELETE</h6>
        <ol>
            <li>
                @Html.Label("User ID:")
                @Html.Label("userid", Model.userid)
            </li>
            <li>
                @Html.Label("Username:")
                @Html.Label(Model.username)
            </li>
        </ol>
        <button>DELETE</button>
    }
</fieldset>

And my Controller:

[HttpPost]
public ActionResult AdminDeleteResult(FormCollection form)
{
     string userid = form["userid"].ToString(); //ERROR HERE
     ...
}

I've try to replace Label by @Html.TextBox("userid") and it works fine. But I want to use Label because I dont want people change it's value. Thank you for your help!

This is not the purpose of the Label you have to use an input . The purpose of the form is to collect data, and the data are kept in form elements .

If you don't want people to change the value (this can be discussed), you can make the input readonly or you can hide it.

Because your View make use of a Model you can use HtmlHelpers with lambda expression to create your form.

@using (Ajax.BeginForm("AdminDeleteResult", "Admin",
                        new AjaxOptions { UpdateTargetId = "div" }))
{
    <div id="div"></div>
    <h6>ARE YOU SURE WANT TO DELETE</h6>
    <ol>
        <li>
            @Html.Label(model => model.userid)
            @Html.TextBoxFor(model => model.userid, new { @readonly="readonly" })

            @* @Html.HiddenFor(model => model.userid) *@
        </li>
        <li>
            @Html.Label(model => model.username)
            @Html.TextBoxFor(model => model.username, new { @readonly="readonly" }) 
        </li>
    </ol>
    <button>DELETE</button>
}

As @man-nemati mentioned, it's better to use the model in your action

[HttpPost]
public ActionResult AdminDeleteResult(UserModel user)
{
   string userid =user.userid; // userid is storred in user
   // ...
}

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