Home > Software engineering >  Using input tag helper in asp.net core - the "value" is empty
Using input tag helper in asp.net core - the "value" is empty

Time:10-09

I am brand new on .net 5 asp tag helpers. I have models like these:

public class MyForm
{
    public String Url { get; set; }
    ...
}


public class MyViewModel
{
    [Required]
    public String Url { get; set; }

    [DisplayName("Seller username")]
    [Required]
    public String SellerName { get; set; }
    ...
}

In my controller I got and URL value for example https://myshop.com/item?id=1234

public IActionResult AddLinkWizardSecond(MyForm form)
{
   var model = new MyViewModel() {
     Url = "https://anotherShop.com/index.html",
     SellerName = "test user 123",
   };
   return PartialView("myView", model);
}

Where my view looks as:

@model MyViewModel
<input asp-for="Url" readonly>
<input asp-for="SellerName">

It is said that the tag helper for input element renders all necessary tags including value tag also. Several examples (on the internet) shows that the rendered html contains <input value="...somevalue...". But - for me this is odd - the rendered html I got in my browser looks as:

<input name="Url" id="Url" value="https://myshop.com/item?id=1234" ... />
<input name="SellerName" id="SellerName" value="" ... />

There must be reason behind this - but I cant catch it. Could somebody give me some ideas why the url contains the posted data instead of the new one, and why the seller name value is empty when I fill these properties? I tried to put the values to ViewBag and ViewData before - but none of them are working:

...
this.ViewData["SellerName"] = model.SellerName;
return PartialView("myView", model);

Is this too much I ask for the tag helpers? They cannot use the current values? Then where the posted value comes from?

Apologizes for the dummy question :( Any advice is greatly welcome which can help me out from the deep swamp of despair where I am now :(

CodePudding user response:

You are correct this is a design choice in the framework. You can read about why it was made, some theory, and also a few work arounds in this blog post.

For example, calling ModelState.Clear(); in your Post action will display the behavior you are looking for.

However, its standard "practice" to use the Post Redirect Pattern regardless, which solves the problem.

  • Related