简体   繁体   English

Razor:如何为只读 TextBox 字段动态分配值?

[英]Razor: How to dynamically assign a value to a read only TextBox field?

I have a read-only text box which is supposed to be initialized to a value dynamically.我有一个read-only文本框,它应该被动态初始化为一个值。 This field is present on a page which is used to enter values to details corresponding to the player that was created in the previous page (I am using RedirectToAction() for this purpose, but was unable to access the passed " PlayerID " value from the controller of the current page. So decided on using TempData . ).此字段出现,这是用来输入值,以对应于在前面的页面中创建的播放器(我使用的详细信息页面上RedirectToAction()用于此目的,但无法访问传递“ PlayerID从”值当前页面的控制器。因此决定使用TempData 。)。 Since the PlayerID changes each time a new player is added, this field should display that value while still remaining read-only.由于每次添加新玩家时PlayerID更改,因此该字段应显示该值,同时仍保持只读状态。 Also, this is a ' required ' field, so the form cannot be submitted until the value is set.此外,这是一个“ required ”字段,因此在设置该值之前无法提交表单。

 @Html.TextBoxFor(model => model.PlayerID, htmlAttributes: new { @readonly = "read-only", @class = "control-label col-md-2", value = @Html.Raw(TempData["PlayerID"]) })

How can I set the value of this field as it is in the TempData["PlayerID"] ?我如何设置这个字段的值,因为它在TempData["PlayerID"]

You can either have a JavaScript that runs on the page load, ex:您可以使用在页面加载时运行的 JavaScript,例如:

@section Scripts
{
 <script>
   $(function(){
    $("#PlayerID").val('@TempData["PlayerID"]');
   });
 </script>
}

Or, you can initialize the Model for the view inside the action, so if your action name was 'PlayerDetails', then you should have something like this:或者,您可以为动作内部的视图初始化模型,因此如果您的动作名称是“PlayerDetails”,那么您应该具有如下内容:

public ActionResult PlayerDetails()
{
  return View(new Player{PlayerID=TempData["PlayerID"]}
}

This way, when the view get bound to the view model, it will be initialized to the passed value.这样,当视图绑定到视图模型时,它将被初始化为传递的值。

You can try below code:你可以试试下面的代码:

@Html.TextBox("PlayerID", @TempData["PlayerID"] ,new { @readonly = "read-only", @class = "control-label col-md-2"})

Or in your case:或者在你的情况下:

@Html.TextBoxFor(model => model.PlayerId, htmlAttributes: new { @readonly = "read-only", @class = "control-label col-md-2", Value = @Html.Raw(TempData["PlayerID"]) })

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

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