This is my method for add food to my chef in my form: I want to add some food that was created before
[HttpGet]
[Route("CreateNewChefFood")]
public async Task<IActionResult> CreateNewChefFood(int id)
{
if (id <= 0) return NotFound();
//var chef= await _foodService.GetChefById(id);
await GetAllFoodList();
await GetAllFoodPriceType();
return View();
}
[HttpPost]
[Route("CreateNewChefFood")]
public async Task<IActionResult> CreateNewChefFood(CreateChefFoodViewModel createChefFoodViewModel)
{
if (ModelState.IsValid)
{
await GetAllFoodList();
await GetAllFoodPriceType();
var result = await _foodService.CreateChefFoodByAdmin(createChefFoodViewModel);
switch (result)
{
case CreateChefFoodResult.NotFound:
return RedirectToAction("NotFound", "Home");
case CreateChefFoodResult.Success:
ViewBag.SuccessText = "Chef food Was Created Successfully";
return RedirectToAction("FilterChefList", "Chef");
}
}
await GetAllFoodList();
await GetAllFoodPriceType();
return View(createChefFoodViewModel);
}
I want to get FoodId in form but I can not and it deos not take FoodSelectedId
this is my view model
public class CreateChefFoodViewModel
{
public int FoodSelectedId { get; set; }
public int ChefId { get; set; }
.
.
.
[Display(Name = "PriceType")]
public List<int> SelectedPriceType { get; set; }
}
and this is part of my view , I send my food name as a View Date to view to and get it on get method correctly
<form asp-controller="Chef" asp-action="CreateNewChefFood" method="post" enctype="multipart/form-data">
<input type="hidden" asp-for="ChefId" />
<input type="hidden" asp-for="FoodId" />
<div class="form-row">
<div class="col-lg-8">
<div class="basic-form">
<div class="form-group">
<label asp-for="FoodSelectedId">Select Food from list:</label>
<select asp-for="FoodId" name="FoodId" class="form-control">
@if (foodList.Any())
{
@foreach (var item in foodList)
{
<option value="@item.FoodId"> @item.FoodTitle </option>
}
}
</select>
<span asp-validation-for="FoodId"></span>
</div>
and I sent food list as view data
@{
ViewData["Title"] = "CreateNewChefFood";
List<FoodViewModel>? foodList = ViewData["FoodList"] as List<FoodViewModel>;
List<PriceTypeTitleViewModel>? priceType = ViewData["PriceType"] as List<PriceTypeTitleViewModel>;
}
Since you specified the input name in form
<select asp-for="FoodId" name="FoodId" class="form-control">
the model defination should also use the correspoding name attribute or the field cannot be delivered.
public class CreateChefFoodViewModel
{
[Display(Name = "FoodId")]
public int FoodSelectedId { get; set; }
...
}