Update label on post using Razor Pages

时间秒杀一切 提交于 2020-01-25 03:05:50

问题


I'm trying to update a label on an http post within a Razor Page. I have a public property called Confirmation as follows:

public string Confirmation { get; set; }

Then I have my post method:

public async Task<IActionResult> OnPostAsync()
{
    //some conditional logic here
    Confirmation = "Settings saved!";
    return Page();
}

In my view I have:

<label asp-for="Confirmation"></label>

However, this renders as:

<label for="Confirmation">Confirmation</label>
  1. I don't want the word "Confirmation" showing up in the view, but rather the set value of the property which is "Setting saved!".
  2. Also, when the post method executes and I set the string property, it doesn't update the label's text.

I've tried setting the Confirmation property in the OnGetAsync() method to "" but this still results in the same text displaying on the label.


回答1:


You should try <label asp-for="Confirmation">@Model.Confirmation</label>.

On a side note, I suspect that you are misusing the label element. It is intended to be paired with a form field of the same name and renders an HTML label. It doesn't help that Win Forms and Web Forms use the <label> control as an all-purpose placeholder for outputting text. In Web Forms it renders as a <span>, which might be more suitable (although you won't get the tag helper assistance).




回答2:


The label tag helper works similar to the Html.LabelFor html helper, which renders the property name (or display name attribute value of the property). Your property name is "Confirmation", hence you are seeing that in the output when using the label tag helper.

If you want to render the value of the property, you may simply print it using normal razor syntax

<label>@Model.Confirmation</label>


来源:https://stackoverflow.com/questions/53034557/update-label-on-post-using-razor-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!