ASP.NET MVC : binding to model within a loop - c#

I'm pretty new to ASP.NET MVC, and I'm trying to figure out if I am able to bind data to my model property from within a loop.
Can I bind it maybe in the onClick event?
At the moment chosenTime is 1/01/0001 12:00:00 AM.
My code for the view is as follows:
#model ResSProject.Models.Sittings.SittingTimesVM
<div class="d-flex justify-content-center">
<div>#Model.RestaurantName</div>
<div class="px-5">#Model.Date.ToString("dd-MMMM-yyyy")</div>
<div>#Model.NumberOfGuests</div>
</div>
<form method="post" asp-action="Reservation">
#{TimeSpan T1 = new TimeSpan(0, 15, 0);
for (var increase = Model.SittingsStart.Subtract(T1); increase < Model.SittingsEnd;)
{
increase = increase.AddMinutes(15);
<input class="btn btn-primary w-50 mx-auto mt-3 " type="button" asp-for="ChosenTime" value="#increase.ToString("HH:mm tt")" />
}
}
<input type="submit" value="Submit" />
<input type="hidden" asp-for=NumberOfGuests />
<input type="hidden" asp-for=Date />
<input type="hidden" asp-for=RestaurantName />
<input type="hidden" asp-for=RestaurantId />
<input type="hidden" asp-for=SittingsStart />
<input type="hidden" asp-for=SittingsEnd />
</form>
My view model class is:
using ResSProject.Data;
using System.ComponentModel.DataAnnotations;
namespace ResSProject.Models.Sittings
{
public class SittingTimesVM
{
public DateTime Date { get; set; }
public int RestaurantId { get; set; }
public string RestaurantName { get; set; }
public int NumberOfGuests { get; set; }
public DateTime ChosenTime { get; set; }
public DateTime SittingsStart { get; set; }
public DateTime SittingsEnd { get; set; }
}
}

Button type element cannot be passed to backend. I think you need set a hidden input and use js to set the chosen time.
Besides, the value of the inputs are just time without date(value="#increase.ToString("HH:mm tt")"). When you post the value, it will bind time with current date to the property ChosenTime. If the SittingsStart and SittingsEnd are not the same date with current now, the chosen time will be not correct.
Whole working demo:
#model SittingTimesVM
<div class="d-flex justify-content-center">
<div>#Model.RestaurantName</div>
<div class="px-5">#Model.Date.ToString("dd-MMMM-yyyy")</div>
<div>#Model.NumberOfGuests</div>
</div>
<form method="post" asp-action="Reservation">
#{TimeSpan T1 = new TimeSpan(0, 15, 0);
for (var increase = Model.SittingsStart.Subtract(T1); increase < Model.SittingsEnd;)
{
increase = increase.AddMinutes(15);
<input class="btn btn-primary w-50 mx-auto mt-3 " type="button" asp-for="ChosenTime"
onclick="GetValue(this)" value="#increase.ToString("dd-MMMM-yyy HH:mm tt")" />
}
}
<input asp-for="ChosenTime" type="hidden"/>
<input type="submit" value="Submit" />
<input type="hidden" asp-for=NumberOfGuests />
<input type="hidden" asp-for=Date />
<input type="hidden" asp-for=RestaurantName />
<input type="hidden" asp-for=RestaurantId />
<input type="hidden" asp-for=SittingsStart />
<input type="hidden" asp-for=SittingsEnd />
</form>
#section Scripts
{
<script>
function GetValue(e)
{
$('input:hidden[name=ChosenTime]').val($(e).val())
}
</script>
}
Backend:
[HttpPost]
public void Reservation(SittingTimesVM model)
{
//do your stuff...
}
Another way I better suggest is to combine <input> elements to one <select> element, and it is no need add any onclick event to set value. It can bind to model property successfully upon you set asp-for="ChosenTime" for the <select> element.
#{
TimeSpan T1 = new TimeSpan(0, 15, 0);
<select type="button" asp-for="ChosenTime">
#for (var increase = Model.SittingsStart.Subtract(T1); increase < Model.SittingsEnd;)
{
increase = increase.AddMinutes(15);
<option value="#increase.ToString("dd-MMMM-yyy HH:mm tt")">#increase.ToString("HH:mm tt")</option>
}
</select>
}

Related

How to use enum value in checkbox and store the accourding in integer number?

I have a string property that corresponds have some checkbox values. I want to use an enum. Enum values want to store on that string property.
My property is in the Model class. It has many properties. I just put only two properties and enum:
public class Client_CIPEnergyCrisis
{
[Display(Name = "What type of assistance are you seeking?")]
public string AssistanceType { get; set; }
[NotMapped]
public List<int> AssistanceTypeList { get; set; }
}
public enum AssistanceTypes
{
[Display(Name = "Assistance with Disconnection")]
AssistanceWithDisconnection = 1,
[Display(Name = "Utility Pole/ Gas line Hookup or Deposit")]
UtilityGaslineHookup = 2,
[Display(Name = "Emergency Heating Fuel")]
EmergencyHeatingFuel = 3,
[Display(Name = "System Repair or Replacement")]
SystemRepair = 4,
[Display(Name = "Anything else ?")]
Anything = 5,
}
This is my view page. That is a partial view. It's used for Insert and Update data.
#model Client_CIPEnergyCrisis
<div><label asp-for="AssistanceType" class="form-label"></label></div>
#foreach (var assistanceType in Enum.GetValues<AssistanceTypes>())
{
<div class="col-md-4 pt-2">
<input class="form-check-input" type="checkbox" value="#((int)assistanceType)" name="AssistanceTypeList">
<label class="form-check-label" for="flexCheckChecked"> #Html.DisplayFor(model => assistanceType) </label>
</div>
}
This is my Add Razor Page add.cshtml page. Here have multiple partial views. We can ignore it. We are passed the needed model.
#page
#model AddCIPEnergyCrisisModel
#{
ViewData["Title"] = "CIP Energy Crisis";
}
<partial name="_DataFormTitlePartial" model='new string("New CIP Energy Crisis")' />
<div class="card dataForm mb-3">
<form method="post">
<partial name="_FamilyIncomeInfoPartial" model="#Model.FamilyIncomeList" />
<partial name="_CIPEnergyCrisisPartial" model="#Model.CIPEnergyCrisis" />
<partial name="_SaveCancelPartial" model="#Model.CCInfo" />
</form>
</div>**strong text**
This is add.cshtml.cs Page.
[BindProperty]
public List<int> AssistanceTypeList { get; set; }
[BindProperty]
public Client_CIPEnergyCrisis CIPEnergyCrisis { get; set; }
public IActionResult OnPost()
{ var selectedAssistantType = string.Join(",", AssistanceTypeList);
CIPEnergyCrisis.AssistanceType = selectedAssistantType;
}
Add feature work well. But when I go to edit. then I face the problem.
This is my Edit Razor Page edit.cshtml.cs page. Here have multiple partial views. We can ignore it. We are passed the needed model.
public void OnGet(int Id)
{
try
{
CIPEnergyCrisis = new Client_CIPEnergyCrisis();
var data = serviceManager.GetClient_CIPEnergyCrisis(Id);
var selectedAssistantType = data.AssistanceType;
CIPEnergyCrisis.AssistanceTypeList = selectedAssistantType
.Split(",")
.Select(int.Parse)
.ToList();
}
}
Maybe I need a if condition in partial page. But I can't do that. may you help me please....
First approach:
You can bind the selected checkbox values to a list of integers then convert the list to comma separated string inside OnPost method. Notice that the name attribute of the checkboxes name="AssistanceTypeList" has the same name as the bound property public List<int> AssistanceTypeList { get; set; }. This is important.
Page:
<div class="col-md-4 pt-2">
<input class="form-check-input" type="checkbox" value="#((int)AssistanceTypes.AssistanceWithDisconnection)" name="AssistanceTypeList"
checked="#(Model.AssistanceTypeList.Contains((int)AssistanceTypes.AssistanceWithDisconnection))">
<label class="form-check-label" for="flexCheckChecked"> Assistance with Disconnection </label>
</div>
<div class="col-md-4 pt-2">
<input class="form-check-input" type="checkbox" value="#((int)AssistanceTypes.UtilityGaslineHookup)" name="AssistanceTypeList"
checked="#(Model.AssistanceTypeList.Contains((int)AssistanceTypes.UtilityGaslineHookup))">
<label class="form-check-label" for="flexCheckChecked"> Utility Pole/ Gas line Hookup or Deposit </label>
</div>
<div class="col-md-4 pt-2">
<input class="form-check-input" type="checkbox" value="#((int)AssistanceTypes.EmergencyHeatingFuel)" name="AssistanceTypeList"
checked="#(Model.AssistanceTypeList.Contains((int)AssistanceTypes.EmergencyHeatingFuel))">
<label class="form-check-label" for="flexCheckChecked"> Emergency Heating Fuel </label>
</div>
<div class="col-md-4 pt-2">
<input class="form-check-input" type="checkbox" value="#((int)AssistanceTypes.SystemRepair)" name="AssistanceTypeList"
checked="#(Model.AssistanceTypeList.Contains((int)AssistanceTypes.SystemRepair))">
<label class="form-check-label" for="flexCheckChecked"> System Repair or Replacement </label>
</div>
<div class="col-md-4 pt-2">
<input class="form-check-input" type="checkbox" value="#((int)AssistanceTypes.Anything)" name="AssistanceTypeList"
checked="#(Model.AssistanceTypeList.Contains((int)AssistanceTypes.Anything))">
<label class="form-check-label" for="flexCheckChecked"> Anything else ? </label>
</div>
PageModel:
[BindProperty]
public List<int> AssistanceTypeList { get; set; }
public void OnGet()
{
var selectedAssistantType = data.AssistanceType;
AssistanceTypeList = selectedAssistantType
.Split(",")
.Select(int.Parse)
.ToList();
}
public void OnPost()
{
// AssistanceTypeList contains the enum values that where checked by the user. We just need to convert the list to comma separated string.
var selectedAssistantType = string.Join(",", AssistanceTypeList);
}
Second approach (my recommendation):
First of all use the Display attribute to set the display name for each enum value. The display name will be shown inside the label of each checkbox.
public enum AssistanceTypes
{
[Display(Name = "Assistance with Disconnection")]
AssistanceWithDisconnection = 0,
[Display(Name = "Utility Pole/ Gas line Hookup or Deposit")]
UtilityGaslineHookup = 1,
[Display(Name = "Emergency Heating Fuel")]
EmergencyHeatingFuel = 2,
[Display(Name = "System Repair or Replacement")]
SystemRepair = 3,
[Display(Name = "Anything else ?")]
Anything = 4,
}
Inside your Page, instead of creating each checkbox "manually", iterate the AssistanceTypes values and create a checkbox for each value. Use #Html.DisplayFor html helper to get the friendly display names for the labels.
#foreach (var assistanceType in Enum.GetValues<AssistanceTypes>())
{
<div class="col-md-4 pt-2">
<input class="form-check-input" type="checkbox" value="#((int)assistanceType)" name="AssistanceTypeList"
checked="#(Model.AssistanceTypeList.Contains((int)assistanceType))">
<label class="form-check-label" for="flexCheckChecked"> #Html.DisplayFor(model => assistanceType) </label>
</div>
}
The PageModel stays the same.
This way if in the future you need to add new values to the AssistanceTypes enum. You don't need to change anything in your Page and PageModel.
https://www.learnrazorpages.com/razor-pages/forms/checkboxes#binding-to-collections
How to use inside a partial example:
_AssistanceTypePartial.cshtml:
#model List<int>
#foreach (var assistanceType in Enum.GetValues<AssistanceTypes>())
{
<div class="col-md-4 pt-2">
<input class="form-check-input" type="checkbox" value="#((int)assistanceType)" name="AssistanceTypeList"
checked="#(Model.Contains((int)assistanceType))">
<label class="form-check-label" for="flexCheckChecked"> #Html.DisplayFor(model => assistanceType) </label>
</div>
}
Inside your view page:
<div class="col-md-12 row ">
<partial name="_AssistanceTypePartial"
model="#Model.AssistanceTypeList">
<div class="col-md-4 pt-2">
<input type="text" class="form-control" placeholder="Explain" />
</div>
</div>

How to filter with dropdownlist, I'm lost. ASP.NET

I have a new challenge, I wanted to perform a filtering in MVC through a dropdownlist, I tried to build my controllers and views based on this site https://www.aspsnippets.com/Articles/Filter-Data-using-DropDownList-in-ASPNet-MVC.aspx, but I don't understand why using two models, and I know that the view will be different from mvc for webGrid but I can still enjoy some parts of the code right? can someone with knowledge guide me?
oh and add to this is I intend that the filtering be done by DateTime, I know that I will be stuck in this forever :)
My Model:
public Nullable<System.DateTime> Data_Registo { get; set; }
public List<SelectListItem> Datas { get; set; }
My Controller:
public ActionResult Index(string listData)
{
Programa model = DataModel(listData);
return View(model);
}
private static Programa DataModel(string listData)
{
using (BaluEntities entities = new BaluEntities())
{
Programa model = new Programa()
{
Datas = (from c in entities.Programa
select new SelectListItem { Text = c.Data_Registo, Value = c.Data_Registo }).Distinct().ToList()
};
return model;
}
}
My View:
<div class="col-md-4">
<form asp-controller="ShowProgramas" asp-action="Index" method="post" role="form">
<div class="form-group">
<div class="alert-danger" asp-validation-summary="ModelOnly"></div>
<label asp-for="ID_Programa"></label>
<select asp-for="ID_Programa"
class="form-control"
asp-items="#(new SelectList(Model.ListofDatas,"Value", "Text"))">
</select>
</div>
<div class="form-group">
<input id="Submit1" class="btn btn-success" type="submit" value="submit" />
</div>
</form>
can someone advise me on a webpage or tutorial? thanks
My Controller:
var listSer = from d in db.Database
orderby d.Date
select d.Date;
var servlist = listSer.Distinct();
ViewBag.startServ = new SelectList(servlist);

Model List property is NULL on Post in controller

So I have tested on a clean project an issue I've been getting, and have done the following code setup for checking if a custom Class object still returns null placed in a List:
VIEW
<div>
<div class="jumbotron">
<h1 class="display-4"><span class="fas fa-user-secret"></span> Babcock Canada - Application Template</h1>
<br />
<div class="alert alert-primary" role="alert">
<span class="fas fa-info-circle"></span>
<span> This is the Babcock Canada MVC Application template for use in developing content-rich web applications.</span>
</div>
<hr class="my-4" />
</div>
<div>
<div class="container-fluid">
#if (!string.IsNullOrEmpty(Model.errorMessage))
{
<div class="alert alert-danger" role="alert">
<span class="fas fa-stop-circle"></span> #Html.DisplayFor(alert => alert.errorMessage)
</div>
}
#if (!string.IsNullOrEmpty(Model.successMessage))
{
<div class="alert alert-success" role="alert">
<span class="fas fa-check-circle"></span> #Html.DisplayFor(alert => alert.successMessage)
</div>
}
<div>
#using (Html.BeginForm("TestAction", "Default", FormMethod.Post))
{
#Html.HiddenFor(m => Model.tester[0].tester)
<button type="submit" class="btn btn-primary">
Submit 1
</button>
}
</div>
<div>
#using (Html.BeginForm("TestAction", "Default", FormMethod.Post))
{
#Html.HiddenFor(m => Model.tester[1].tester)
<button type="submit" class="btn btn-primary">
Submit 2
</button>
}
</div>
</div>
</div>
TestClass.cs
namespace Test.Models
{
public class TestClass
{
public string tester { get; set; }
}
}
MODEL
namespace Test.Models
{
/// <summary>
/// This is the default template model.
/// </summary>
public class DefaultModel : SharedModel
{
public string errorMessage = string.Empty;
public string successMessage = string.Empty;
public List<TestClass> tester { get; set; }
public DefaultModel()
{
}
public void Init()
{
tester = new List<TestClass>
{
new TestClass { tester = "Testing..." },
new TestClass { tester = "Testing2..." }
};
}
}
}
CONTROLLER
[HttpPost]
public ActionResult TestAction(DefaultModel model)
{
return View(model);
}
So the result is that the second one returns NULL in the list, but the first one returns just fine.
In my other project index 0 of a list looped in the same way returns the error: "An item with the same key has already been added."
So what am I doing wrong?
try using the helper Html.Hidden() instead
<div>
#using (Html.BeginForm("TestAction", "Default", FormMethod.Post))
{
#Html.Hidden("tester", Model.tester[0].tester)
<button type="submit" class="btn btn-primary">
Submit 1
</button>
}
</div>
<div>
#using (Html.BeginForm("TestAction", "Default", FormMethod.Post))
{
#Html.Hidden("tester", Model.tester[1].tester)
<button type="submit" class="btn btn-primary">
Submit 2
</button>
}
</div>
Turns out it doesn't work when the form is inside the loop, has to be outside and reference an ID value through the submit button holding the name "ID" and the value of that list item.
Suppose using Html.Hidden() would work, but that isn't what was required for the project.

RuntimeBinderException: Cannot perform runtime binding on a null reference

I'm making a create item page, and in this create item page there is a popup modal table where we can choose the type of UoM that we want. And normally when this form is submitted with all of the fields filled in, it saved the values into the database. But when the form is submitted with one or some or all of the fields not filled in, it supposed to give some error message that the fields are required. But it didn't and it shows this error.
These are my code
ItemController
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Threading.Tasks;
using CRMandOMS.Models;
using CRMandOMS.ViewModels;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace CRMandOMS.Controllers
{
public class ItemController : Controller
{
private readonly IItemRepository _itemRepository;
private readonly IUoMRepository _uoMRepository;
public ItemController(IItemRepository itemRepository, IUoMRepository uoMRepository)
{
_itemRepository = itemRepository;
_uoMRepository = uoMRepository;
}
// GET: /<controller>/
public ViewResult Index()
{
var model = _itemRepository.GetAll();
return View(model);
}
public ViewResult Details(Guid? id)
{
Item item = _itemRepository.GetById(id.Value);
return View(item);
}
[HttpGet]
public ViewResult Create()
{
ItemCreateViewModel itemCreateViewModel = new ItemCreateViewModel()
{
UoMs = _uoMRepository.GetAll()
};
return View(itemCreateViewModel);
}
[HttpPost]
public IActionResult Create(ItemCreateViewModel model)
{
if (ModelState.IsValid)
{
Item newItem = new Item
{
Name = model.Name,
Price = model.Price,
UoMId = model.UoMId
};
_itemRepository.Insert(newItem);
return RedirectToAction("Details", new { id = newItem.Id });
}
return View();
}
}
}
Create
#model CRMandOMS.ViewModels.ItemCreateViewModel
#{
ViewData["Title"] = "Item Create";
}
<h2>Item Create</h2>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a asp-controller="Item" asp-action="Index">Item</a></li>
<li class="breadcrumb-item active" aria-current="page">Create</li>
</ol>
</nav>
<form enctype="multipart/form-data" asp-controller="Item" asp-action="Create" method="post" class="mt-3">
<div class="form-group row">
<label asp-for="Name" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Name" class="form-control" placeholder="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Price" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Price" class="form-control" placeholder="Price" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="UoMId" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="UoMId" id="uomid" class="form-control" hidden />
<div class="input-group mb-3">
<input id="uomname" type="text" class="form-control" placeholder="UoM" aria-label="UoM" aria-describedby="button-uom" disabled>
<div class="input-group-append">
<button class="btn btn-outline-success" type="button" id="button-uom" data-toggle="modal" data-target="#uoMLookupTableModal">Select UoM</button>
</div>
</div>
<span asp-validation-for="UoMId" class="text-danger"></span>
</div>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-10">
<a asp-controller="Item" asp-action="Index" class="btn btn-light">Back</a>
<button type="submit" class="btn btn-success">Create</button>
</div>
</div>
</form>
#{
await Html.RenderPartialAsync("_UoMLookup");
}
#section scripts {
<script>
$(document).ready(function () {
var uoMTable = $("#uoMTable").DataTable({
"columnDefs": [
{
"targets": [0],
"visible": false
}
],
"order": [[1, "asc"]]
});
$('#uoMTable tbody').on('click', 'tr', function () {
if ($(this).hasClass('table-success')) {
$(this).removeClass('table-success');
}
else {
uoMTable.$('tr.table-success').removeClass('table-success');
$(this).addClass('table-success');
}
});
$("#getUoM").click(function () {
var uomdata = uoMTable.row('.table-success').data();
//alert(uomdata[0]);
$('#uomid').val(uomdata[0]);
//alert(uomdata[1]);
$('#uomname').val(uomdata[1]);
});
});
</script>
}
_UoMLookup
<div class="modal fade" id="uoMLookupTableModal" tabindex="-1" role="dialog" aria-labelledby="uoMLookupTableModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<table id="uoMTable" class="table table-striped table-bordered table-bordered nowrap" style="width:100%">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td>Description</td>
</tr>
</thead>
<tbody>
#foreach (UoM uom in Model.UoMs)
{
<tr>
<td class="uom-id">#uom.Id</td>
<td class="uom-name">#uom.Name</td>
<td>#uom.Description</td>
</tr>
}
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
<button id="getUoM" type="button" class="btn btn-success" data-dismiss="modal">Select</button>
</div>
</div>
</div>
</div>
ItemCreateViewModel
using CRMandOMS.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CRMandOMS.ViewModels
{
public class ItemCreateViewModel
{
[Required]
[MaxLength(100, ErrorMessage = "Name cannot exceed 100 characters")]
public string Name { get; set; }
[Required(ErrorMessage = "{0} is required")]
[Range(1000, 999999999)]
public int Price { get; set; }
[Required]
public Guid UoMId { get; set; }
public IEnumerable<UoM> UoMs { get; set; }
public string PhotoPath { get; set; }
}
}
In the HTTP POST Create method (ItemController) if the model is not valid (so ModelState.IsValid == false) you are not passing a model to your View. Ensure passing a valid model, as shown in the controller methods tutorial.
But when the form is submitted with one or some or all of the fields not filled in, it supposed to give some error message that the fields are required. But it didn't and it shows this error.
You do not have a reference to validation scripts, make sure you have _ValidationScriptsPartial.cshtml in Shared folder, then modify your code:
#section scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
<script>
//...
</script>
}
For the error on your page, just like other community has said, it is likely that the model state is invalid and it execute return View() without returning any data to create view.
However,your partial view does not allow the Model.UoMs to be null.
In your Create Post action, if the model contains UoMs, you could just use
return View(model)
otherwise ,assign UoMs data to model like what you have done in Create Get action, then return it to view.
You could always use a breakpoint on the Post action to debug the result.

Html.Hidden() generating blank values in HTML

I have a form on my view:
#using (Html.BeginForm("ClearData", "MemberPass", FormMethod.Post))
{
<div>
#foreach (var property in ViewData.ModelMetadata.Properties)
{
#Html.Hidden(property.PropertyName, property.Model)
}
</div>
<button>Clear</button>
}
and the following action methods:
public ActionResult Index()
{
MemberPassInfoViewModel memberPassInfoViewModel = new ServiceUtilities().GetEventDetails(DateTime.Now.Date);
return View("Index", memberPassInfoViewModel);
}
public ActionResult GetMemberPassInfo(MemberPassInfoViewModel currentMemberPassInfoValues)
{
MemberPassInfoViewModel updatedMemberPassInfoViewModel = new ServiceUtilities().GetMemberPassInfoViewModel(currentMemberPassInfoValues);
return View("Index", updatedMemberPassInfoViewModel);
}
public ActionResult ClearData(MemberPassInfoViewModel currentMemberPassInfoValues)
{
MemberPassInfoViewModel updatedMemberPassInfoViewModel = new ServiceUtilities().ClearData(currentMemberPassInfoValues);
return View("Index", currentMemberPassInfoValues);
}
In debug I can see that the model's two properties are present. However when I view the generated HTML, one of the properties has a blank value:
<input id="SearchCode" name="SearchCode" type="hidden" value="23" />
<input id="FullName" name="FullName" type="hidden" value="" />
I noticed that this could be fixed by replacing:
#Html.Hidden(property.PropertyName, property.Model)
with:
<input type="hidden" value="#property.Model" name="#property.PropertyName" />
Which generates:
<input type="hidden" value="23" name="SearchCode" />
<input type="hidden" value="Alex Robert" name="FullName" />
Why does the #Html.Hidden() method not work, but explicitly writing the <input> tag does work?

Categories

Resources