How to get a value from a dynamic form? - asp.net-core

I am using .NET Core with razor pages and I have a model as a list of object as below. Can anyone tell me how to do it? I searched many forums, seems only using controller can do it.
Here is the razor cshtml form I'm using:
<form id="form" method="post" data-ajax="true" data-ajax-method="post" >
<h4>Performance Rating</h4>
<div>
<p>
<mark>
#Model.CommonContents.Find(x => x.ContentId.Equals(24)).ContentText
</mark>
</p>
</div>
<div class="table-responsive">
<table id="contentTbl" class="display nowrap table table-striped table-bordered">
<thead>
<tr>
<th width="25%">
#Model.CommonContents.Find(x => x.ContentId.Equals(25)).ContentText
</th>
<th style="font-size:xx-small" width="5%">(a)<br /> #Model.CommonContents.Find(x => x.ContentId.Equals(26)).ContentText</th>
<th style="font-size:xx-small" width="5%">(b) <br />#Model.CommonContents.Find(x => x.ContentId.Equals(27)).ContentText</th>
<th style="font-size:xx-small" width="5%">(c)=(a)X(b)<br />#Model.CommonContents.Find(x => x.ContentId.Equals(28)).ContentText</th>
<th>#Model.CommonContents.Find(x => x.ContentId.Equals(29)).ContentText</th>
<th width="5%">#Model.CommonContents.Find(x => x.ContentId.Equals(30)).ContentText</th>
</tr>
</thead>
<tbody>
#{ var j = 0; }
#{ var QuestionId = 0;}
#for (int k = 0; k < Model.QuesAns.Count; k++)
{
j = k + 1;
QuestionId = Model.QuesAns[k].QuestionId;
<tr>
<td>
<h5>#j. #Html.DisplayFor(modelitem => Model.QuesAns[k].TitleText)</h5>
<p>#Html.DisplayFor(modelitem => Model.QuesAns[k].ContentText)</p>
<input type="hidden" name="QuestionId_#j" , id="QuestionId_#j" value="#QuestionId" />
</td>
<td align="center">
<lable id="Weighting_#j">#Html.DisplayFor(modelitem => Model.QuesAns[k].Weighting)</lable>%
</td>
<td align="center">
<select class="form-control p-0" name="Weighting_#j" id="Weighting_#j" asp-for="#Model.QuesAns[k].Weighting">
<option value="0"></option>
<option value="5">5</option>
<option value="4.5">4.5</option>
<option value="4">4</option>
<option value="3.5">3.5</option>
<option value="3">3</option>
<option value="2.5">2.5</option>
<option value="2">2</option>
<option value="1.5">1.5</option>
<option value="1">1</option>
</select>
</td>
<td align="center"><lable id="WeightingMarks_#j"></lable></td>
<td>
<textarea class="form-control" rows="10" name="Comment_#j" id="Comment_#j" asp-for="#Model.QuesAns[k].Answer" ></textarea>
</td>
<td>
(#Html.DisplayFor(modelitem => Model.QuesAns[k].AttachNum))
<span class="k-icon k-i-attachment-45"></span>
</td>
</tr>
}
<tr style="background-color:burlywood">
<td align="right">
<input type="hidden" value="#Model.QuesAns.Count" name="TotalQues" id="TotalQues" />
<b>
#Model.CommonContents.Find(x => x.ContentId.Equals(31)).ContentText
</b>
</td>
<td>100%</td>
<td></td>
<td><label id="TotalWeightingMarks"></label></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="row">
<input type="text" id="formAction" name="formAction" style="display:none">
<input id="btnSubmit" type="submit" value="Confirmed" class="btn btn-block btn-danger" />
</div>
</div>
</form>
javascript part
$(document).ready(function () {
$('#btnSubmit').click(function () {
$('#formAction').val("submit");
}); });
the coding page like this
[BindProperty]
public List<VAppraisalQuestionAnswer> qa { set; get; }
public IActionResult OnPost(string formAction)
{
//i want to get value from the from
var abc = qa; // qa is return count= 0
return Page();
}
Here is the model
public class VAppraisalQuestionAnswer
{
[StringLength(50)]
public string StaffCode { get; set; }
[StringLength(50)]
public string DeptCode { get; set; }
[StringLength(10)]
public string AppraisalPeriodCode { get; set; }
public int QuestionId { get; set; }
[StringLength(int.MaxValue)]
public string TitleText { get; set; }
[StringLength(int.MaxValue)]
public string ContentText { get; set; }
public int Weighting { get; set; }
public string Answer { get; set; }
public int AttachNum { get; set; }
public int DspOrd { get; set; }
}

I already found the solution. All I need to do is add IFormCollection to the OnPostAsync, then IFormCollection returns the array value.
like this:
public async Task<IActionResult> OnPostAsync(IFormCollection Form) {

To bind a simple type list object, the name attribute in the input text should in this format: [index].property. The index must start from 0 and be continuous. Change the table body like below:
<tbody>
#{ var j = 0; }
#{ var QuestionId = 0;}
#for (int k = 0; k < Model.QuesAns.Count; k++)
{
j = k + 1;
QuestionId = Model.QuesAns[k].QuestionId;
<tr>
<td>
<h5>#j. #Html.DisplayFor(modelitem => Model.QuesAns[k].TitleText)</h5>
<p>#Html.DisplayFor(modelitem => Model.QuesAns[k].ContentText)</p>
<input type="hidden" name="[#k].QuestionId" , id="QuestionId_#j" value="#QuestionId" />
</td>
<td align="center">
<lable id="Weighting_#j">#Html.DisplayFor(modelitem => Model.QuesAns[k].Weighting)</lable>%
</td>
<td align="center">
<select class="form-control p-0" name="[#k].Weighting" id="Weighting_#j" asp-for="#Model.QuesAns[k].Weighting">
<option value="0"></option>
<option value="5">5</option>
<option value="4.5">4.5</option>
<option value="4">4</option>
<option value="3.5">3.5</option>
<option value="3">3</option>
<option value="2.5">2.5</option>
<option value="2">2</option>
<option value="1.5">1.5</option>
<option value="1">1</option>
</select>
</td>
<td align="center"><lable id="WeightingMarks_#j"></lable></td>
<td>
<textarea class="form-control" rows="10" name="[#k].Comment" id="Comment_#j" asp-for="#Model.QuesAns[k].Answer"></textarea>
</td>
<td>
(#Html.DisplayFor(modelitem => Model.QuesAns[k].AttachNum))
<span class="k-icon k-i-attachment-45"></span>
</td>
</tr>
}
<tr style="background-color:burlywood">
<td align="right">
<input type="hidden" value="#Model.QuesAns.Count" name="TotalQues" id="TotalQues" />
</td>
<td>100%</td>
<td></td>
<td><label id="TotalWeightingMarks"></label></td>
<td></td>
<td></td>
</tr>
</tbody>

Related

ASP.NET Core - How would I set a name with ID of HTML element on CSHTML

How would I set a name with ID of HTML element on CSHTML?
<tr>
<td>
#item.Items.ItemID
</td>
<td>
#item.Items.ItemModelDescription
</td>
<td class="text-right">
<input id="#item.Items.ItemID + 'UnitPrice'" class="form-control text-right" value="#item.Items.ItemUnitPrice" />
</td>
<td class="text-right">
<input id="#item.Items.ItemID + 'Quantity'" class="form-control text-right" value="#item.Quantity" oninput="return change_quantity('#item.Items.ItemID')"/>
</td>
<td class="text-right">
#(item.Quantity * item.Items.ItemUnitPrice)
</td>
<td>
<a class="btn btn-sm btn-danger btn-rounded" asp-controller="purchaseorderheader" asp-action="Remove" asp-route-id="#item.Items.ItemID"><span class="fa fa-trash"></span></a>
</td>
</tr>
I can't get the value of HTML element using javascript is there anyway or proper way of setting an id of each quantity input? Or any keywords to search regarding this one.
According to your code and description, I assume you want to calculate the cost based on the Quantity and the ItemUnitPrice. If that is the case, please refer to the following sample code, you can refer it to change your code:
ViewModel:
public class ItemViewModel
{
public int ItemId { get; set; }
public string ItemDescription { get; set; }
public decimal ItemUnitPrice { get; set; }
public decimalc Quantity { get; set; }
}
Index.cshtml: we could set the id attribute like this id='Quantity_#item.ItemId', after rendering, the output like Quantity_XXX:
#model IEnumerable<WebApplication6.Models.ItemViewModel>
<table class="table">
<thead>
<tr>
...
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.ItemId
</td>
<td>
#item.ItemDescription
</td>
<td class="text-right">
<input id="ItemUnitPrice_#item.ItemId" class="form-control text-right" type="text" value="#item.ItemUnitPrice" />
</td>
<td class="text-right">
<input id='Quantity_#item.ItemId' class="form-control text-right txtquantity" type="text" value="#item.Quantity" oninput="return change_quantity(this,#item.ItemId)" />
</td>
<td class="text-right">
#(item.Quantity * item.ItemUnitPrice)
</td>
<td>
<a class="btn btn-sm btn-danger btn-rounded" asp-controller="purchaseorderheader" asp-action="Remove" asp-route-id="#item.ItemId"><span class="fa fa-trash"></span></a>
</td>
</tr>
}
</tbody>
</table>
Then at the end of the Index.cshtml page, add the following JavaScript: we could use the parent() and closest() method to find the current row, and then find the relates elements in this row.
#section Scripts{
<script>
function change_quantity(e, itemid) {
//find the item unit price.
var price = $("#" + "ItemUnitPrice_" + itemid).val();
//find the quantity value.
var quantity = $("#" + "Quantity_" + itemid).val();
//calculate the cost and change the html content.
$(e).parent().closest("tr").find(".text-right:last").html((price * quantity).toFixed(2).toString());
}
</script>
}
The output like this:
you can use this approach
#foreach (var item in Model)
{
<tr id="tr-#item.ItemId">
<td>
#item.ItemId
</td>
<td>
#item.ItemDescription
</td>
<td class="text-right">
<input id="ItemUnitPrice_#item.ItemId" class="form-control text-right" type="text" value="#item.ItemUnitPrice" />
</td>
<td class="text-right">
<input id='Quantity_#item.ItemId' class="form-control text-right txtquantity" type="text" value="#item.Quantity" oninput="return change_quantity(this,#item.ItemId)" />
</td>
<td class="text-right">
#(item.Quantity * item.ItemUnitPrice)
</td>
<td>
<a class="btn btn-sm btn-danger btn-rounded" asp-controller="purchaseorderheader" asp-action="Remove" asp-route-id="#item.ItemId"><span class="fa fa-trash"></span></a>
</td>
</tr>
}

asp-validation-for not working under foreach due to same name issue

I am using asp-validation-for under foreach and facing following issues. suppose 3 text controls generated with foreach. I am using the [required] model annotation. "objGenExaminationTemplateChoicesModel" object is of ICollection in main model.
if first text controls is empty system is showing error message with
all 3 text controls.
if second or third is empty system is not
showing any message but don't proceed to post page due to model
error.
<table id="dtChoices" class="table table-borderless table-striped">
<thead class="bg-primary">
<tr>
<th class="text-left"><label asp-for="#Model.objGenExaminationTemplateChoicesModel.FirstOrDefault().ChoiseDescription" class="control-label"></label></th>
<th style="width:30px"><span class="sidenav-icon icon icon-plus-square pull-right" style="font-size:large"> </span></th>
</tr>
</thead>
<tbody>
#foreach (var objGenExaminationTemplateChoiceModel in Model.objGenExaminationTemplateChoicesModel)
{
iCounter = iCounter + 1;
<tr>
<td class="text-left form-group form-group-sm">
<input type="text" asp-for="#objGenExaminationTemplateChoiceModel.ChoiseDescription" class="form-control">
<span asp-validation-for="#objGenExaminationTemplateChoiceModel.ChoiseDescription" class="text-danger"></span>
</td>
<td>
<a href="#" class="text-warning btnDeleteRow" data-toggle="modal" data-target="#deleteConfirmationModalAlert">
<span class="sidenav-icon icon icon-trash pull-right" style="font-size:large"> </span>
</a>
</td>
</tr>
}
</tbody>
The objGenExaminationTemplateChoicesModel is a list model,so the model binding system would find the name by [i].propertyName.Change your code like below:
#model TestVmodel
<form>
<table id="dtChoices" class="table table-borderless table-striped">
<thead class="bg-primary">
<tr>
<th class="text-left"><label asp-for="#Model.objGenExaminationTemplateChoicesModel.FirstOrDefault().ChoiseDescription" class="control-label"></label></th>
<th style="width:30px"><span class="sidenav-icon icon icon-plus-square pull-right" style="font-size:large"> </span></th>
</tr>
</thead>
<tbody>
#{ var iCounter = 0;}
#for (int i = 0; i < Model.objGenExaminationTemplateChoicesModel.Count(); i++)
{
iCounter = iCounter + 1;
<tr>
<td class="text-left form-group form-group-sm">
<input type="text" asp-for="#Model.objGenExaminationTemplateChoicesModel[i].ChoiseDescription" class="form-control">
<span asp-validation-for="#Model.objGenExaminationTemplateChoicesModel[i].ChoiseDescription" class="text-danger"></span>
</td>
<td>
<a href="#" class="text-warning btnDeleteRow" data-toggle="modal" data-target="#deleteConfirmationModalAlert">
<span class="sidenav-icon icon icon-trash pull-right" style="font-size:large"> </span>
</a>
</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="aa" />
</form>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
My testing model:
public class TestVmodel
{
public List<ObjGenExaminationTemplateChoicesModel> objGenExaminationTemplateChoicesModel { get; set; }
}
public class ObjGenExaminationTemplateChoicesModel
{
[Required]
public string ChoiseDescription { get; set; }
}
Result:

Can not send list of objects from view to controller using tag helper in asp.net core 2.2

I have the following view and I want to send list of object from view to controller and I used asp-for tag helper for data binding but action in controller receives null
#model IEnumerable<GoodsList>
<form method="post" asp-action="SubmitList" asp-controller="Submit">
<table class="table table-bordered">
<thead>
<tr>
<th width="2%">number</th>
<th width="20%">Name</th>
<th width="20%">Brand</th>
<th width="20%">Quantity</th>
<th width="20%">Scale</th>
<th width="8%">operation</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.Number</td>
<td><input type="text" readonly="readonly" asp-for="#item.GoodsName" class="form-control" /></td>
<td><input type="text" readonly="readonly" asp-for="#item.BrandName" class="form-control" /></td>
<td><input type="text" readonly="readonly" asp-for="#item.Quantity" class="form-control" /></td>
<td><input type="text" readonly="readonly" asp-for="#item.ScaleName" class="form-control" /></td>
<td>
<select class="form-control" asp-items="#(new SelectList(item.Status,"Id","Name"))">
</select>
</td>
</tr>
}
<tr>
<td colspan="6">
<textarea class="form-control" rows="3" readonly="readonly" cols="5">#Model.Select(s => s.Description).First()</textarea>
</td>
</tr>
</tbody>
</table>
<a class="btn btn-primary">Back</a>
<input type="submit" value="Submit" class="btn btn-success" style="width:auto">
</form>
And Here is my controller which receives null
[HttpPost]
//It receives null
public IActionResult SubmitList(IEnumerable<GoodsList> model)
{
return View();
}
And the Model
public class GoodsList
{
public GoodsList()
{
Status = new List<ApprovalStatus>();
}
public int Number { get; set; }
public string GoodsName { get; set; }
public string BrandName { get; set; }
public int? Quantity { get; set; }
public string UserName { get; set; }
public string RankName { get; set; }
public int? RequestId { get; set; }
public string ScaleName { get; set; }
public IList<ApprovalStatus> Status { get; set; }
}
Any solution?
Thanks in advance
Change your razor view like below:
#model IEnumerable<GoodsList>
<form method="post" asp-action="SubmitList" asp-controller="Submit">
<table class="table table-bordered">
<thead>
<tr>
<th width="2%">number</th>
<th width="20%">Name</th>
<th width="20%">Brand</th>
<th width="20%">Quantity</th>
<th width="20%">Scale</th>
<th width="8%">operation</th>
</tr>
</thead>
<tbody>
#{ var i = 0;}
#foreach (var item in Model)
{
<tr>
<td>#item.Number</td>
<td><input type="text" readonly="readonly" name="[#i].GoodsName" asp-for="#item.GoodsName" class="form-control" /></td>
<td><input type="text" readonly="readonly" name="[#i].BrandName" asp-for="#item.BrandName" class="form-control" /></td>
<td><input type="text" readonly="readonly" name="[#i].Quantity" asp-for="#item.Quantity" class="form-control" /></td>
<td><input type="text" readonly="readonly" name="[#i].ScaleName" asp-for="#item.ScaleName" class="form-control" /></td>
<td>
<select class="form-control" name="[#i].Status[0].Id" asp-items="#(new SelectList(item.Status,"Id","Name"))">
</select>
</td>
</tr>
i++;
}
<tr>
<td colspan="6">
<textarea class="form-control" rows="3" readonly="readonly" cols="5">#Model.Select(s => s.Description).First()</textarea>
</td>
</tr>
</tbody>
</table>
<a class="btn btn-primary">Back</a>
<input type="submit" value="Submit" class="btn btn-success" style="width:auto">
</form>
Result:
Another way:
#model IList<GoodsList> //change this
//..
<tbody>
#for(var i = 0;i<Model.Count();i++)
{
<tr>
<td>#Model[i].Number</td>
<td><input type="text" readonly="readonly" asp-for="#Model[i].GoodsName" class="form-control" /></td>
<td><input type="text" readonly="readonly" asp-for="#Model[i].BrandName" class="form-control" /></td>
<td><input type="text" readonly="readonly" asp-for="#Model[i].Quantity" class="form-control" /></td>
<td><input type="text" readonly="readonly" asp-for="#Model[i].ScaleName" class="form-control" /></td>
<td>
<select class="form-control" asp-for="#Model[i].Status[0].Id" asp-items="#(new SelectList(Model[i].Status,"Id","Name"))">
</select>
</td>
</tr>
}
<tr>
<td colspan="6">
<textarea class="form-control" rows="3" readonly="readonly" cols="5">#Model.Select(s => s.Description).First()</textarea>
</td>
</tr>
</tbody>
</table>
<a class="btn btn-primary">Back</a>
<input type="submit" value="Submit" class="btn btn-success" style="width:auto">
</form>

During View data not getting captured in the Controller in ASP.Net Core 2.0 MVC. I am new to ASP.Net core MVC

I am trying to implement Update/Edit functionality in ASP.Net Core using Razor. Below is the view page.
After clicking Submit button the view page is POSTed to the "GetCustomerForEdit" method of the controller as mentioned below in the code. But unfortunately the edited data from the view is not transferred to the controller method "GetCustomerForEdit", parameter "EditCustomer" of type "GetAllCustDetails".
Since i am new to ASP.net Core is there something i am missing or not doing right in the View or Controller?
VIEW CODE:
<form asp-action="GetCustomerForEdit">
<div>
<table class="tables1">
#foreach (var item in Model.Custs)
{
<tr>
<th style="width:300px;" colspan="2">Update Customers
Details</th>
</tr>
<tr style="visibility:hidden">
<td><input asp-for="#item.CustomerId" type="hidden" />/td>
</tr>
<tr>
<td>First Name</td>
<td><input asp-for="#item.FirstName" autofocus
class="textbox1" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input asp-for="#item.LastName" class="textbox1" />
</td>
</tr>
<tr>
<td>Sex</td>
<td><select asp-for="#item.Sex" class="textbox1" asp-
items="#(new SelectList(ViewBag.listofitems, "Sex", "Sex"))"></select>
</td>
</tr>
<tr>
<td>Age</td>
<td><input asp-for="#item.Age" class="textbox1"
type="text" /></td>
</tr>
<tr>
<td style="width: 177px">Address1</td>
<td><input asp-for="#item.Address1" class="textbox1"
type="text" /></td>
</tr>
<tr>
<td>Address2</td>
<td><input asp-for="#item.Address2" class="textbox1"
type="text" /></td>
</tr>
<tr>
<td>State</td>
<td><input asp-for="#item.State" class="textbox1"
type="text" /></td>
</tr>
<tr>
<td>City</td>
<td><input asp-for="#item.City" class="textbox1"
type="text" /></td>
</tr>
<tr>
<td>Pin</td>
<td><input asp-for="#item.Pin" class="textbox1"
type="text" /></td>
</tr>
<tr>
<td>Phone</td>
<td><input asp-for="#item.Phone" class="textbox1"
type="text" /></td>
</tr>
<tr>
<td>Mobile</td>
<td><input asp-for="#item.Mobile" class="textbox1"
type="text" /></td>
</tr>
<tr>
<td>Email</td>
<td><input asp-for="#item.Email" class="textbox1"
type="text" /></td>
</tr>
}
<tr class="trfooter">
<td colspan="2">
<input class="submit" type="submit" value="Save" />
<input type="reset" class="submit" value="Reset" />
<input type="button" class="submit" value="Cancel" />
</td>
</tr>
</table>
#if (TempData["RecordSave"] != null)
{
<p>#TempData["RecordSave"]</p>
}
</div>
</form>
MODEL CODE:
public class GetAllCustDetails
{
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Customer> Custs;
}
Where Customer model:
public class Customer
{
public int CustomerId { get; set; }
[Required(ErrorMessage =" Please enter First Name!")]
public string FirstName { get; set; }
[Required(ErrorMessage =" Please enter Last Name!")]
public string LastName { get; set; }
[Required(ErrorMessage =" Please enter Sex!")]
public string Sex { get; set; }
[Range(0,99)]
[Required(ErrorMessage =" Please enter valid Age!")]
public int Age { get; set; }
[Required(ErrorMessage =" Please enter valid Adddress!")]
public string Address1 { get; set; }
public string Address2 { get; set; }
[Required(ErrorMessage =" Please enter State!")]
public string State { get; set; }
[Required(ErrorMessage =" Please enter valid State!")]
public string City { get; set; }
[Required(ErrorMessage =" Please enter valid Pin!")]
public int Pin { set; get; }
public long Phone { set; get; }
public long Mobile { get; set; }
[EmailAddress(ErrorMessage =" Please enter valid Email!")]
[Required(ErrorMessage = "Email is required field!")]
public string Email { get; set; }
}
CONTROLLER CODE: [HttpGet is working fine]
[HttpGet]
public IActionResult GetCustomerForEdit(Int16? Id)
{
GetAllCustDetails getCustForEdit;
clsCustomerDAL getCust;
getCust = new clsCustomerDAL();
getCustForEdit = getCust.GetCustomerForUpdate(Id);
SexDropDown();// this is dropdown getting populated from DB
return View(getCustForEdit);
}
[HttpPost]
public IActionResult GetCustomerForEdit([Bind] GetAllCustDetails
EditCustomer)
{
bool retVal = false;
int CustId = 0;
string Fname;
string Lname;
if(ModelState.IsValid)
{
clsCustomerDAL updateCust = new clsCustomerDAL();
retVal = updateCust.DALEditCustomer(EditCustomer);
if(retVal == true)
{
ModelState.Clear();
}
return View("getCustomerDetails");
}
return View("IndexPage");
}
Since you need to pass a List of Customer from View to controller, for model binding, you could specify name property for each input.
Edit view:
#model GetAllCustDetails
<form asp-action="GetCustomerForEdit">
<div>
<table class="tables1">
#{int i = 0;}
#foreach (var item in Model.Custs)
{
<tr>
<th style="width:300px;" colspan="2">
Update Customers
Details
</th>
</tr>
<tr style="visibility:hidden">
<td><input asp-for="#item.CustomerId" type="hidden" name="Custs[#i].CustomerId" />/td>
</tr>
<tr>
<td>First Name</td>
<td>
<input asp-for="#item.FirstName" name="Custs[#i].FirstName" autofocus class="textbox1" />
</td>
</tr>
//other <tr> properties
<tr>
<td>Email</td>
<td>
<input asp-for="#item.Email" name="Custs[#i].Email" class="textbox1" type="text" />
</td>
</tr>
i++;
}
<tr class="trfooter">
<td colspan="2">
<input class="submit" type="submit" value="Save" />
<input type="reset" class="submit" value="Reset" />
<input type="button" class="submit" value="Cancel" />
</td>
</tr>
</table>
#if (TempData["RecordSave"] != null)
{
<p>#TempData["RecordSave"]</p>
}
</div>
</form>
Post action:
[HttpPost]
public IActionResult GetCustomerForEdit([Bind] GetAllCustDetails EditCustomer)

system.argumentnullexception value cannot be null on Model.Any()

I am getting "system.argumentnullexception" on the Model.Any() line when I submit the form and the table in database is currently empty. the code of view are as follow.
#using System.Linq
#model IEnumerable<Al_sehrawi.Models.tbl_Packing>
#{
ViewBag.Title = "AddBox2";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AddBox2</h2>
#{
if (Model.Any())
{
foreach (var i in Model)
{
<form action="~/Packing/AddBox2" method="post">
<table>
<tr>
<td>
Id:
#{int counter = i.packing_id + 1;}
<input name="id" type="number" value="#counter" />
</td>
</tr>
<tr>
<td>
Name :
</td>
<td>
<input name="packingName" type="text" />
</td>
</tr>
<tr>
<td>
Unit :
</td>
<td>
<input name="unit" type="text" />
</td>
</tr>
<tr>
<td>
Quantity of 1st Packing :
</td>
<td>
<input name="quantity1" type="number" />
</td>
</tr>
<tr>
<tr>
<td>
Quantity of 2nd Packing :
</td>
<td>
<input name="quantity2" type="number" />
</td>
</tr>
<tr>
<td>
<input name="Submit1" type="submit" value="submit" />
</td>
</tr>
</table>
</form>
}
}
else
{
<form action="~/Packing/AddBox2" method="post">
<table>
<tr>
<td>
Id:
<input name="id" type="number" value="1" />
</td>
</tr>
<tr>
<td>
Name :
</td>
<td>
<input name="packingName" type="text" />
</td>
</tr>
<tr>
<td>
Unit :
</td>
<td>
<input name="unit" type="text" />
</td>
</tr>
<tr>
<td>
Quantity of 1st Packing :
</td>
<td>
<input name="quantity1" type="number" />
</td>
</tr>
<tr>
<tr>
<td>
Quantity of 2nd Packing :
</td>
<td>
<input name="quantity2" type="number" />
</td>
</tr>
<tr>
<td>
<input id="Submit1" type="submit" value="submit" />
</td>
</tr>
</table>
</form>
}
}
The code in PackingController are as follow.
public ActionResult AddBox2()
{
PackingModel c = new PackingModel();
var id = c.getNextId();
return View(id);
}
[HttpPost]
public ActionResult AddBox2(int id, string packingName, string unit, int quantity1, int quantity2)
{
PackingModel p = new PackingModel();
p.addBox2(id, packingName, unit, quantity1, quantity2);
return View();
}
and the Model is
public bool addBox2(int id, string packingName, string unit,int quantity1, int quantity2)
{
try
{
using (POSEntities1 db = new POSEntities1())
{
tbl_Packing p = new tbl_Packing();
tbl_packing_box2a b1 = new tbl_packing_box2a();
tbl_packing_box2b b2 = new tbl_packing_box2b();
p.name = packingName;
p.unit = unit;
b1.quantiity = quantity1;
b1.tbl_packing_box_id = id;
int a_Id;
var result = db.tbl_packing_box2a.OrderByDescending(b => b.tbl_packing_box1a_id).Take(1).ToList();
foreach (var item in result)
{
a_Id = item.tbl_packing_box1a_id;
b2.quantity = quantity2;
b2.tbl_packing_box2a_id = a_Id;
db.tbl_Packing.Add(p);
db.tbl_packing_box2a.Add(b1);
db.tbl_packing_box2b.Add(b2);
db.SaveChanges();
}
}
}
catch (Exception)
{
return false;
}
return true;
}
First check if model is empty and then try Model.Any()
#if (Model != null)
{
if (Model.Any())
{
....
}
}