Mehmet Eren Yener Mehmet Eren Yener - 2 months ago 9
ASP.NET (C#) Question

Hidden Field not passing value to controller

This is myModel

public class myModel : myBaseModel
public string AccountName { get; set; }
public string BankName { get; set; }
public string BranchCode { get; set; }

I am getting the AccountName,BankName and BranchCode from the view with textBoxFor

@Html.LabelFor(m => m.AccountName, GetContentBody(101111))
@Html.TextBoxFor(m => m.AccountName)
@Html.ValidationMessageFor(m => m.AccountName)

Problem is I dont need the Accountname text box anymore, however I am not allowed to remove AccountName from the model and I should assign this value in the view.

So I planned to change this textbox with html.hiddenFor with its value, the problem is hiddenfield is passing the account name to the controller as a null.

**my question is why hiddenfield is passing its value as a null?**

I removed this

@Html.TextBoxFor(m => m.AccountName)

and added instead of it

@Html.HiddenFor(m=>m.AccountName, new { @Value = "defaultUserName" });

Answer Source

You are doing wrong. you have to use this overload or this overload for it, it looks like you missed a comma to separate the extension method arguments:

Instead of:

@Html.HiddenFor(m=>m.AccountName new { @Value = "defaultUserName" })

you need to do:

@Html.HiddenFor(m=>m.AccountName, new { @Value = "defaultUserName" })