0

I am using asp.net core razor engine. I am trying to set a default value for a text area. I have looked at other posts and I seem to following the advice. However the default value I set does not show up.

Here is my code in my .cshtml page

@Html.TextAreaFor(d=>d.Users_id, new {@Value =TempData["id"]})

1 Answer 1

1

That's the wrong way to set a default value. The value of bound inputs is determined by ModelState, which itself is composed of the values from Request, ViewData/ViewBag and finally Model. Despite setting the value attribute to something explicitly, Razor will back fill the value with whatever it finds in ModelState for that property.

If you want a default value, then you can either set it on the property itself:

C# 6

public int Users_Id { get; set; } = 1;

C# Previous

private int? users_Id;
public int Users_Id
{
    get { return users_Id ?? 1; }
    set { users_Id = value; }
}

Or, set the value manually on your model in your action:

model.Users_Id = TempData["id"];

Obviously, since you're using TempData here, you'll have to go with the second option, but the first method is better if you're dealing with a constant default.

Just bear in mind that, Model is the last source for ModelState, so if you do something like have an action param named users_id (case insensitive) or set ViewBag.Users_Id (again, case insensitive), that will take priority over everything else.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.