简体   繁体   English

在ASP.NET MVC 4 Razor中,如何获取@ Html.Label的值(文本)?

[英]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. 我尝试用@Html.TextBox("userid")替换Label,它工作正常。 But I want to use Label because I dont want people change it's value. 但是我想使用Label,因为我不希望人们改变它的价值。 Thank you for your help! 谢谢您的帮助!

This is not the purpose of the Label you have to use an input . 这不是使用input Label的目的。 The purpose of the form is to collect data, and the data are kept in form elements . form的目的是收集数据,并将数据保存在表单元素中

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. 如果您不希望人们更改值(可以讨论),则可以将input readonly ,也可以将其隐藏。

Because your View make use of a Model you can use HtmlHelpers with lambda expression to create your form. 由于您的视图使用模型 ,因此可以将Latda表达式与HtmlHelpers一起使用来创建表单。

@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 正如@ man-nemati所提到的,最好在您的操作中使用模型

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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