I have a controller action that returns a partial view with an empty model. But when I inspect the browser it shows the hidden element for Id
has a value. why is this happening?
Here's my code:
Controller:
[HttpGet]
public async Task<IActionResult> GetItemForm(int? id)
{
try
{
//var account = await _uow.CashAccounts.GetAsync((int)id);
//if (account == null)
// return Json(new NotFound());
var model = new AccountHistoryFormModel();
//model.AccountId = (int)id;
return PartialView("_AddFundForm", model);
}
catch (Exception ex)
{
return Json(new InternalError(ex.Message));
}
}
View:
@using Trucking.WebUI.Models.BankAccount
@model AccountHistoryFormModel
@using (Html.BeginForm("save", "accounthistory", FormMethod.Post, new { id = "add-fund-form", @class = "row g-2" }))
{
@Html.HiddenFor(x => x.Id)
//@Html.HiddenFor(x => x.AccountId)
<div >
@Html.LabelFor(x => x.Amount, new { @class = "form-label form-label-sm" })
@Html.TextBoxFor(x => x.Amount, new { @class = "form-control form-control-sm" })
@Html.ValidationMessageFor(x => x.Amount, "", new { @ })
</div>
<div >
@Html.LabelFor(x => x.DateDeposit, new { @class = "form-label form-label-sm" })
@Html.TextBoxFor(x => x.DateDeposit, "{0:yyyy-MM-dd}", new { @type = "date", @class = "form-control form-control-sm" })
@Html.ValidationMessageFor(x => x.DateDeposit, "", new { @class = "invalid-feedback" })
</div>
}
AccountHistoryFormModel:
public class AccountHistoryFormModel : BaseModel
{
public AccountHistoryFormModel()
{
Action = "DEPOSIT";
DateDeposit = DateTime.Now;
}
public int AccountId { get; set; }
[Range(1.0, double.MaxValue, ErrorMessage = "Amount must not be 0.")]
public decimal Amount { get; set; }
public string Action { get; }
[Display(Name = "Date Deposit")]
public DateTime DateDeposit { get; set; }
}
Browser:
Thank you in advance.
CodePudding user response:
This is exactly what the strongly typed HTML Helper for a hidden field Html.HiddenFor()
do. It takes as a parameter System.Linq.Expressions.Expression<Func<TModel,TProperty>>
expression and generate a
MvcHtmlString
.
In your case because the view model has Id
property with value 2
the following HTML string was generated:
<input id="Id" name="Id" type="hidden" value="2" />
CodePudding user response:
Check AccountHistoryFormModel's constructor ! probably you set id property on this class.