create new record via multiple model in one view - c#

I have faced a problem which is can't save the record into the database. I have 3 model in one view. I have done the view and getting error about this
An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Validation failed for one or more entities.
See 'EntityValidationErrors' property for more details.
here is my view
<div class="container">
<div class="row">
<div class="col-lg-12 management-title">
<h1>Create New Invoice</h1>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<form>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyID, "CompanyID",new { #Name="CompanyID"})
#Html.DropDownList("CompanyID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.CompanyID , "", new { #class = "text-danger" })
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#bill_to_company">Company Details</a>
</h4>
</div>
<div id="bill_to_company" class="panel-collapse collapse in wrapper-company-details">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyName)
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.CompanyName, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyAddress)
#Html.TextAreaFor(model => model.PurchaseInvoiceTable.CompanyAddress, new { #class = "form-control golbal_textarea" })
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.startdate)
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.startdate, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
</div>
<div class="form-group">
</div>
</div>
</div>
</div>
</div>
<h2>Product List</h2>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#product_list">Product List</a>
</h4>
</div>
<div id="product_list" class="panel-collapse collapse in input_fields_wrap">
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel panel-default product_wrapper">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#product' + x + '">Product</a>
</h4>
</div>
<div id="product'+x+'" class="panel-collapse collapse in">
<div class="panel-group">
<div class="panel panel-default">
<div class="col-lg-12">
<div class="col-lg-3">
<label>Product</label>
#Html.TextAreaFor(model => model.PurchaseInvoiceDetailsTable.Product)
</div>
<div class="col-lg-6">
<label>Description</label>
#Html.TextAreaFor(model => model.PurchaseInvoiceDetailsTable.ProductDescription)
</div>
'<div class="col-lg-2 form-group">
<label>Price</label>
#Html.TextBoxFor(model => model.PurchaseInvoiceDetailsTable.Price)
</div>
</div>
</div>
</div>
</div>
cancel
</div>
</div>
</div>
</div>
</div>
</div>
<button class="add_field_button btn btn-primary pull-right">Add More Fields</button>
<div class="wrapper-company-details">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.Remark)
#Html.TextAreaFor(model => model.PurchaseInvoiceTable.Remark, new { #class = "form-control", #style = "resize:none;" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Remark, "", new { #class = "text-danger" })
</div>
<h1>Payment Term Area</h1>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#payment_term_collapse">Payment Term</a>
</h4>
</div>
<div id="payment_term_collapse" class="payment_term_area panel-collapse collapse in">
<table class="table table-bordered">
<tr style="background-color:black; color:white;">
<th style="width:70%;">
<input type="text" class="form-control" id="payment_term" placeholder="Type how many terms client want" />
</th>
<th style="width:30%;">
<button class="btn btn-default" id="add_payment_terms">Add</button>
</th>
</tr>
</table>
<table class="table table-bordered">
<tr style="background-color:black; color:white;">
<th style="width:70%;">
Payment Term
</th>
<th style="width:30%;">
Amount
</th>
</tr>
<tr style="background-color:black; color:white;">
<th style="text-align:right;">
Discount
</th>
<th>
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.Discount, new { #class = "form-control discount price_textbox", #id = "discount", #Value = "0" })
</th>
</tr>
<tr style="background-color:black; color:white;">
<th style="text-align:right;">
Total
</th>
<th>
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.Subtotal, new { #class = "form-control price_textbox total", #id = "totval", #Value = "0" })
</th>
</tr>
</table>
<div id="payment_term_area">
<h2>Payment Terms</h2>
<div class="payment_term_wrapper" style="padding:0; margin:0;">
<table class="table table-bordered" style="width:95%;">
<tr style="background-color:black; color:white;" class="payment_term_wrapper">
<th style="width:70%;">
<input class="pull-right payment_terms_label_input" style="background-color:black; color:white;"></input>
</th>
<th style="width:30%;">
#Html.TextBoxFor(model => model.PaymentTerm.Amount)
</th>
</tr>
X
</table>
</div>
</div>
<table class="table table-bordered">
<tr style="background-color:black; color:white;">
<th style="text-align:right; width:70%;">
Last Payment
</th>
<th style="width:30%;">
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.Total, new { #class = "form-control price_textbox", #id = "lastpayment", #Value = "0" })
</th>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="col-lg-12">
</div>
<div class="col-lg-12">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.Category, "Category")
#Html.DropDownList("Category", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Category, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.Method)
#Html.DropDownListFor(model => model.PurchaseInvoiceTable.Method, new List<SelectListItem>
{
new SelectListItem() {Text = "Cash", Value="Cash"},
new SelectListItem() {Text = "Cheque", Value="Cheque"},
new SelectListItem() {Text = "Bank Transfer", Value="BankTransfer"}
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Method, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.PaymentTerm, "PaymentTerm", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.PurchaseInvoiceTable.PaymentTerm, new List<SelectListItem>
{
new SelectListItem() {Text = "1", Value="1"},
new SelectListItem() {Text = "2", Value="2"},
new SelectListItem() {Text = "3", Value="3"}
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.PaymentTerm, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.Status, new { #class = "form-control", #Value = "Active" })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.Status, new { #class = "form-control", #Value = "Active" })
#Html.HiddenFor(model => model.PaymentTerm.Status, new { #class = "form-control", #Value = "Active" })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.first_created, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.first_created, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PaymentTerm.first_created, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.first_created_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.first_created_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PaymentTerm.first_created_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.last_updated, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.last_updated, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PaymentTerm.last_updated, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.last_updated_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.last_updated_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PaymentTerm.last_updated_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
</div>
<div class="form-group">
<div>
<input type="submit" value="Create" class="btn btn-primary pull-right" />
#Html.ActionLink("Back", "Index", null, new { #class = "btn btn-small btn-danger pull-right", #style = "margin-right:2%;" })
</div>
</div>
</div>
</form>
}
</div>
</div>
here is my controller
public ActionResult Create()
{
ViewBag.CompanyID = new SelectList(db.SupplierTables, "SupplierID", "SupplierID");
ViewBag.Product = new SelectList(db.ProductTables, "ProductID", "ProductID");
ViewBag.Category = new SelectList(db.CategoryTables, "CategoryID", "CategoryID");
ViewBag.PaymentTerm = new SelectList(db.PaymentTerms, "TermID", "TermID");
return View();
}
[HttpPost]
public ActionResult Create([Bind(Include = "PurchaseInvoiceTable,PurchaseInvoiceDetailsTable,PaymentTerm")]InvoiceWrapper model)
{
if (ModelState.IsValid)
{
db.PurchaseInvoiceTables.Add(model.PurchaseInvoiceTable);
db.PurchaseInvoiceDetailsTables.Add(model.PurchaseInvoiceDetailsTable);
db.PaymentTerms.Add(model.PaymentTerm);
db.SaveChanges();
//model.PurchaseInvoiceTable.PurchaseInvoiceID = model.PurchaseInvoiceDetailsTable.InvoiceID = model.PaymentTerm.InvoiceID;
return RedirectToAction("Index");
}
ViewBag.CompanyID = new SelectList(db.SupplierTables, "SupplierID", "SupplierID");
ViewBag.Product = new SelectList(db.ProductTables, "ProductID", "ProductID");
ViewBag.Category = new SelectList(db.CategoryTables, "CategoryID", "CategoryID");
ViewBag.PaymentTerm = new SelectList(db.PaymentTerms, "TermID", "TermID");
return View(model);
}

The exception you are getting means that one or more of the entities properties that you are trying to save is not valid. e.g. The column is defined as not null and the property you are trying to save is null.
In order to see the validation errors you can use this:
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}",
validationError.PropertyName,
validationError.ErrorMessage);
}
}
}
credits

Related

ASPNET Core MVC Partial view from JQuery and controller

Goal: I'm trying to make a page that has the user enter in an address, then click a button that will verify it with a FedEx API. With the new verified address (now with the extra postal code from FedEx), I want to have the user verify that the new address is correct using a modal popup all without reloading the page.
Issue: I'm having a problem where the partial isn't showing and I'm not sure what I'm doing wrong.
Here's the View:
#model AirmotionEcommerceWebsite.Models.Home.DeliveryAddressModel
#{
ViewBag.Title = "Shipping Address";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<div class="container">
#Html.AntiForgeryToken()
<form class="form-horizontal">
<h4>Shipping Address</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<partial id="ValidateAddress"></partial>
<div class="form-group">
<h5>Name</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Attention To</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strAttnTo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strAttnTo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street 2</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>City</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#{
IEnumerable<SelectListItem> dataItems = ViewBag.states;
}
<div class="form-group">
<h5>State</h5>
<div class="col-md-10">
#Html.DropDownListFor(model => model.State.IntStateId, dataItems, "-- Select --", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.State.IntStateId, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<h5>Zip</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strZip, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strZip, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" class="btn btn-primary" data-ajax-method="get" data-toggle="ajax-modal" data-target="#ValidateAddress"
data-url="#Url.Action("GetValidationOnAddress", new { model = Model })">
Verify Address
</button>
</div>
</div>
</form>
</div>
<script>
$(function () {
var PlaceHolderElement = $('#ValidateAddress');
$('button[data-toggle="ajax-modal"]').click(function (event) {
event.preventDefault();
var url = $(this).data('url');
// get the form containing the submit button
var form = $(this).closest('form')
// serialize all the fields in the form
var model = form.serialize();
// the the request to the url along with the form (model) data
$.get(url, model).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
$('#ValidateAddress').modal('show');
})
})
})
</script>
Here's the Controller:
[HttpGet]
public IActionResult GetValidationOnAddress(DeliveryAddressModel model)
{
FedexAPI fedexAPI = new FedexAPI();
List<string> listOfStreets = new List<string>();
listOfStreets.Add(model.strStreet1);
listOfStreets.Add(model.strStreet2);
var newAddress = fedexAPI.ValidateAddress(listOfStreets, model.strCity, model.State.StrStateCode, model.strZip, "US");
if (newAddress.customerMessages.Contains("INTERPOLATED.STREET.ADDRESS"))
{
// Address is not valid
model.ErrorMessage = "The address entered could not be found. Please double check your address. If issues perssist, please contact our office _________";
}
else
{
model.strStreet1 = newAddress.streetLinesToken[0];
if (newAddress.streetLinesToken.Count > 1)
model.strStreet2 = newAddress.streetLinesToken[1];
model.strCity = newAddress.city;
model.strZip = newAddress.postalCode;
}
return PartialView("_AddressValidationPartial", model);
}
And lastly here's the Partial View:
#model AirmotionEcommerceWebsite.Models.Home.DeliveryAddressModel
<div class="modal fade" id="ValidateAddress">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="ValidateAddressLabel">Validate Address</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="Create">
<div class="form-group">
#if (Model.ErrorMessage == null)
{
<h5>#Model.strName</h5>
#if (Model.strAttnTo != null)
{<h5>#Model.strAttnTo</h5>}
<h5>#Model.strStreet1</h5>
#if (Model.strStreet2 != null)
{<h5>#Model.strStreet2</h5>}
<h5>#Model.strCity</h5>
<h5>#Model.State.StrStateCode</h5>
<h5>#Model.strZip</h5>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Accept Changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Edit</button>
</div>
}
else
{
<h4>#Model.ErrorMessage</h4>
}
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-save="modal">Save Changes</button>
</div>
</div>
</div>
</div>
I checked the console and found it was not able to find my partial view. Quick file move and it's working now! Thanks to #viveknuna for helping me notice this!

how to display foreign key fields using asp.net mvc?

Basically I wanted to display foreign key fields in asp.net cshtml. I have two tables roles and admin respectively. The foreign key relationship shows that for every admin there is a Role which has to be set.
I have done the part of adding role using role name. But when it comes to deleting or updating and such functionality I am not able to figure out the way to display the role name or other role details instead of roleId. I understand the concept of the doing, yet I do not get the right answer in asp.net mvc.
The following code for the cshtml, where I wanted to show the role name instead of role id.
#model IEnumerable<FastFactsTestPortalMVCApp.Models.Administrator>
#{
ViewBag.Title = "ViewAdmin";
Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<h2>ViewAdmin</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.AdminId)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminFirstName)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminLastName)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminEmail)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminUserName)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminPassword)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminContactNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminDesignation)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminRoleId)
</th>
<th>
#Html.DisplayNameFor(model => model.CreatedAt)
</th>
<th>
#Html.DisplayNameFor(model => model.UpdatedAt)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.AdminId)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminFirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminLastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminEmail)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminUserName)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminPassword)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminContactNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminDesignation)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminRoleId)
</td>
<td>
#Html.DisplayFor(modelItem => item.CreatedAt)
</td>
<td>
#Html.DisplayFor(modelItem => item.UpdatedAt)
</td>
<td>
#Html.ActionLink("Update", "UpdateAdmin", item) |
#Html.ActionLink("Delete", "DeleteAdmin", item)
</td>
</tr>
}
</table>
The below code is for the the admin controller method - ViewAdmin:
public ActionResult ViewAdmin()
{
List<Models.Administrator> administrators = new List<Models.Administrator>();
FastFactsTestPortalMapper<Administrator, Models.Administrator> mapobj = new FastFactsTestPortalMapper<Administrator, Models.Administrator>();
FastFactsTestPortalRepository repObj = new FastFactsTestPortalRepository();
var lstEntityAdmins = repObj.GetAdministrators();
foreach(var admin in lstEntityAdmins)
{
administrators.Add(mapobj.Translate(admin));
}
return View(administrators);
}
Like wise when I update, the cshtml for the update functionality is :
#model FastFactsTestPortalMVCApp.Models.Administrator
#{
ViewBag.Title = "UpdateAdmin";
Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<h2 class="text-center">Update Admin</h2>
#using (Html.BeginForm("SaveUpdatedAdmin","Admin"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Administrator</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.AdminId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminFirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminFirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminFirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminLastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminLastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminLastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminEmail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminEmail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminUserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminUserName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminUserName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminContactNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminContactNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminContactNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminDesignation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminDesignation, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminDesignation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminRoleId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminRoleId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminRoleId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreatedAt, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreatedAt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreatedAt, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UpdatedAt, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UpdatedAt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UpdatedAt, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "ViewAdmin")
</div>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
The controller method for the update functionality is
public ActionResult UpdateAdmin(Models.Administrator administrator)
{
var admindetails = administrator;
return View(administrator);
}
public ActionResult SaveUpdatedAdmin(Models.Administrator administrator)
{
if (ModelState.IsValid)
{
try
{
FastFactsTestPortalRepository repObj = new FastFactsTestPortalRepository();
FastFactsTestPortalMapper<Models.Administrator, Administrator> mapObj = new FastFactsTestPortalMapper<Models.Administrator, Administrator>();
var status = repObj.UpdateAdmin(mapObj.Translate(administrator));
if (status)
{
return RedirectToAction("ViewAdmin");
}
else
{
return View("Error");
}
}
catch (Exception)
{
return View("Error");
}
}
return View("UpdateAdmin", administrator);
}
The Output which I get is :
AdminId AdminFirstName AdminLastName AdminEmail AdminUserName AdminPassword AdminContactNumber AdminRoleId
1 Srinivas Muralidharan sm1043#gmail.com admin admin 09677299116 1
I want to change the AdminRoleId to RoleName : Administrator which is already in the database. Also I wanted to keep the change for all the other functionalities.
Kindly could you explain how to come over such problems?

How to turn HTML TextBoxFor into Labels in Razor

I have a form, I would like where I have Html.TextBoxFor into labels is this possible?
#* title *#
<div class="form-group">
<label class="control-label col-md-4">Song Title</label>
<div class="col-md-4">
#foreach (var t in Model.OriginalWork.AlternativeTitles)
{<label class="control-label text-muted">#t.Title</label>
}
</div>
</div>
#* Alternative Titles *#
<div class="form-group">
#Html.LabelFor(m => m.OriginalWork.AlternativeTitles, new { #class = "control-label col-md-4" })
<div class="col-md-8">
<div class="row">
<div class="tag-container tags col-md-12" data-bind="foreach: AlternateTitles">
#foreach (var t in Model.OriginalWork.AlternativeTitles)
{<span class="tm-tag tm-tag-info" data-bind="hidden: IsDeleted">
#t.Title
</span>
}
</div>
</div>
</div>
</div>
#* Duration *#
<div class="form-group mbn">
<label class="control-label col-md-4 pull-left hidden-sm" for="DurationMinutes">Duration</label>
<div class="col-md-1 mb15">
#Html.LabelFor(m => m.OriginalWork.DurationMins, new { #class = "control-label pull-left hidden-md hidden-lg hidden-xl" })
#Html.TextBoxFor(m => m.OriginalWork.DurationMins, new { #class = "form-control isDisabled", placeholder = "Mins...", data_bind = "value: DurationMins" })
#Html.ValidationMessageFor(m => m.OriginalWork.DurationMins, string.Empty, new { #class = "text-danger" })
</div>
<div class="col-md-1 mb15">
#Html.LabelFor(m => m.OriginalWork.DurationSecs, new { #class = "control-label pull-left hidden-md hidden-lg hidden-xl" })
#Html.TextBoxFor(m => m.OriginalWork.DurationSecs, new { #class = "form-control isDisabled", placeholder = "Secs...", data_bind = "value: DurationSecs" })
#Html.ValidationMessageFor(m => m.OriginalWork.DurationSecs, string.Empty, new { #class = "text-danger" })
</div>
</div>
#* Performing Artists *#
<div class="form-group">
#Html.LabelFor(m => m.OriginalWork.PerformingArtistNames, new { #class = "control-label col-md-4" })
<div class="col-md-8">
<div class="row">
<div class="tag-container tags col-md-12" data-bind="foreach: PerformingArtistNames">
#foreach (var t in Model.OriginalWork.PerformingArtistNames)
{<span class="tm-tag tm-tag-info" data-bind="hidden: IsDeleted">
#t.Firstname #t.Lastname
</span>
}
</div>
</div>
</div>
</div>
#* remix and samples *#
<div class="form-group">
#Html.LabelFor(m => m.OriginalWork.IsRemix, new { #class = "control-label col-md-4" })
<div class="col-md-8">
<div class="admin-form theme-primary">
<div class="radio-custom radio-primary mt10 mr10 pull-left">
#Html.RadioButtonFor(m => m.OriginalWork.IsRemix, true, new { #class = "control-label col-md-4" })
<label for="IsRemixYes">Yes</label>
</div>
<div class="radio-custom radio-primary mt10 pull-left">
#Html.RadioButtonFor(m => m.OriginalWork.IsRemix, false, new { #class = "control-label col-md-4" })
<label for="IsRemixNo">No</label>
</div>
</div>
</div>
</div>
#*Contains Sample Radio Button*#
<div class="form-group">
#Html.LabelFor(m => m.OriginalWork.ContainsSample, new { #class = "control-label col-md-4" })
<div class="col-md-8">
<div class="admin-form theme-primary">
<div class="radio-custom radio-primary mt10 mr10 pull-left">
#Html.RadioButtonFor(m => m.OriginalWork.ContainsSample, true, new { #class = "control-label col-md-4" })
<label for="ContainsSampleYes">Yes</label>
</div>
<div class="radio-custom radio-primary mt10 pull-left">
#Html.RadioButtonFor(m => m.OriginalWork.ContainsSample, false, new { #class = "control-label col-md-4" })
<label for="ContainsSampleNo">No</label>
</div>
</div>
</div>
</div>
#* ISWC *#
<div class="form-group">
#Html.LabelFor(m => m.OriginalWork.Iswc, new { #class = "control-label col-md-4" })
<div class="col-md-4">
#Html.TextBoxFor(m => m.OriginalWork.Iswc, new { #class = "form-control isDisabled", placeholder = "ISWC", data_bind = "value: Iswc" })
#Html.ValidationMessageFor(m => m.OriginalWork.Iswc, string.Empty, new { #class = "text-danger" })
</div>
</div>
</div>
</fieldset>
If you want to disable your radio button, assuming you're using razor syntax, you can use:
#Html.RadioButtonFor(m => m.SomeModelItem, "false")
And this should put you on the right track.

ASP.Net MVC Viewmodel goes null to controller from View

I want to export my Viewmodel from my view to my controller which is receiving it in a method, this is my view:
#using Resources
#model MyProject.ViewModel.CertificationViewModel
#{
ViewBag.Title = Resources.titleCertificationList;
#section css
{
<link href="#Url.Content("~/layout/css/stylesformador.css")" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
}
}
<div class="mainblock">
<div class="block-group">
<div class="ttitle title">#HIQResources.titleEdit</div>
</div>
#using (Html.BeginForm("Edit", "Certification", FormMethod.Post, new { id = "form1" }))
{
#Html.AntiForgeryToken()
<div class="md-content">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.pdf, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#*<input type="file" name="file" />*#
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control inputForm", #type="file" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Code, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Code, new { htmlAttributes = new { #class = "form-control inputForm", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.Code, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SelectedEntityId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.SelectedEntityId, Model.EntitiesDrop, htmlAttributes: new { #class = "form-control inputForm" })
#Html.HiddenFor(model => model.SelectedEntityId)
#Html.ValidationMessageFor(model => model.SelectedEntityId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StatusId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.StatusId, Model.StatusDrop, htmlAttributes: new { #class = "form-control inputForm" })
#Html.HiddenFor(model => model.StatusId)
#Html.ValidationMessageFor(model => model.StatusId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Result, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Result, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Result, "", new { #class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Observation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Observation, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Observation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1">
<div class="col-md-8">
<table class="table table-bordered">
<tr>
<th class="col-md-2">
#Html.DisplayNameFor(model => model.FileName)
</th>
<th class="col-md-2">Ficheiro</th>
</tr>
#foreach (var item in Model.teste)
{
<tr>
<td>
#if (item.FileName == null)
{
<h5>Não existem ficheiros para esta certificação.</h5>
}
else
{
#Html.DisplayFor(modelItem => item.FileName)
}
</td>
<td>
#if (item.FileName == null)
{
<h5>Não existem ficheiros para esta certificação.</h5>
}
else
{
Download
#*Delete*#
<input type="submit" value="Edit" id="Delete" class="btn btn-default btn-sm btn-detail" />
}
#*#Html.ActionLink("Download", "Certification", "Download", new { id = Model.Id })*#
</td>
</tr>
}
</table>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-8">
<input type="submit" value="#HIQResources.buttonSave" class="btn btn-default btn-sm btn-detail" />
#Html.ActionLink(HIQResources.buttonBack, "CertificationList", new { id = Model.StudentId, nome = Model.StudentName }, new { #class = "btn btn-default btn-sm btn-edit" })
</div>
</div>
</div>
</div>
}
</div>
#section Scripts {
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/HIQTrainingScripts/Certification/Edit.js"></script>
<script>
$("#Date").datepicker({ dateFormat: 'yy/mm/dd' });
$("#Delete").click(function () {
var vm = $('#Model').serialize();
alert(vm)
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
url: "/Certification/Edit",
type: "POST",
data: {
__RequestVerificationToken: token,
vm: vm,
click: "deu",
},
sucess: function (result) {
alert("sucess");
}
});
});
</script>
}
This is the method in my controller:
[Authorize(Roles = "Admin, Staff")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CertificationViewModel vm, string click) {
if (click == "deu")
{
int lol = _servicesFactory.GetService<ICertificationManager>().DeleteFile(vm, GetLoggedUser());
return View(vm);
}
}
The value of my ViewModel comes always as null to my Jquery variable and I don't know why, because it should come with the info from the view to the controller in order for me, to execute my task.
Am I missing something ?

dynamically add 'add button' inside for loop

I have foreach loop which contains some data. What I want is if user click on add button, save the details to the database as well as empty input values and go to the next iteration of the foreach loop.
Following is my code that I tried so far.
#model ModelLib.Models.PaymentDetails
#{
Layout = null;
var fullCount = Model.listRoomDetails.Max(x => x.FullCount);
}
<div class="row">
#Html.AntiForgeryToken()
<div class="row">
<div>You have to add <span id="passangerCount">#fullCount</span> Passanger details</div>
#foreach (var item in Model.listRoomDetails) {
<span>#item.RoomType RoomType Passanger Count : </span ><div id="#item.RoomType">#item.Count</div>
}
#foreach (var item in Model.listRoomDetails) {
<div class="row">
Room Type - <span id="existing_RoomType">#item.RoomType</span>
Room Category - <span id="existing_RoomCategory">#item.RoomCategory</span>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-info" style="background-color:#ffffff;">
<div class="panel-heading" id="payment_heading" style="border-style: double; text-align: center; background-color: #f59e6b; border-color: black; color: black; font-weight: bold;">Add Payment Details<i class="fa fa-chevron-circle-down" style="font-size: 24px; float: right; margin-right: -17px; margin-top: 6px;"></i></div>
<div class="panel-body" id="payment_body">
<div class="row">
<div class="col-sm-4">
<div class="col-sm-6">
#Html.LabelFor(model => model.TicketNumber, new { #class = "label_class" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(model => model.TicketNumber, new { type = "text", maxlength = "13", #id = "ticketNumber", #class = "form-control", data_toggle = "tooltip", title = "Enter Ticket Name" })
</div>
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-6">
#Html.LabelFor(model => model.PassangerName, new { #class = "label_class" })
</div>
<div class="col-sm-6">
#Html.TextBoxFor(model => model.PassangerName, new { #id = "passangerName", #class = "form-control", data_toggle = "tooltip", title = "Enter passanger Name" })
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-6">
#Html.LabelFor(model => model.PassportNumber, new { #class = "label_class" })
</div>
<div class="col-sm-6">
#Html.TextBoxFor(model => model.PassportNumber, new { #id = "passportNumber", #class = "form-control", data_toggle = "tooltip", title = "Enter passport number", maxlength = 8 })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="col-sm-6">
#Html.LabelFor(model => model.PkgVal, new { #class = "label_class" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(model => model.PkgVal, new { type = "number", #min = "0", #id = "pkgVal", data_toggle = "tooltip", title = "Enter valid pkg value", #class = "form-control" })
</div>
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-6">
#Html.LabelFor(model => model.AirFare, new { #class = "label_class" })
</div>
<div class="col-sm-6">
#Html.TextBoxFor(model => model.AirFare, new { type = "number", #min = "0", #id = "airFare", data_toggle = "tooltip", title = "Enter valid airfare", #class = "form-control" })
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-6">
#Html.LabelFor(model => model.Tax, new { #class = "label_class" })
</div>
<div class="col-sm-6">
#Html.TextBoxFor(model => model.Tax, new { type = "number", #min = "0", #id = "tax", data_toggle = "tooltip", title = "Enter valid tax", #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="col-sm-6">
#Html.LabelFor(model => model.DateChangeFee, new { #class = "label_class" })
</div>
<div class="col-sm-6">
#Html.TextBoxFor(model => model.DateChangeFee, new { type = "number", #min = "0", #id = "dateChangeFee", data_toggle = "tooltip", title = "Enter valid date change fee value", #class = "form-control" })
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-6">
#Html.LabelFor(model => model.CommissionToAgent, new { #class = "label_class" })
</div>
<div class="col-sm-6">
#Html.TextBoxFor(model => model.CommissionToAgent, new { type = "number", #min = "0", #id = "commissionToAgent", data_toggle = "tooltip", title = "Enter valid commission to agent value", #class = "form-control" })
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-6">
#Html.LabelFor(model => model.VMPDNumber, new { #class = "label_class" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(model => model.VMPDNumber, new { type = "text", maxlength = "13", #id = "vmpdNumber", data_toggle = "tooltip", title = "Enter vmpd number", #class = "form-control" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="col-sm-6">
#Html.LabelFor(model => model.EMDNumber, new { #class = "label_class", #style = "margin-top: -3px;" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(model => model.EMDNumber, new { type = "text", maxlength = "13", #id = "emdNumber", data_toggle = "tooltip", title = "Enter emd number", #class = "form-control" })
</div>
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-6">
#Html.LabelFor(model => model.RoomType, new { #class = "label_class", #style = "margin-top: -3px;" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBox(item.RoomType, new { type = "text", #id = "roomType", #class = "form-control" })
</div>
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-6">
#Html.LabelFor(model => model.RoomCat, new { #class = "label_class", #style = "margin-top: -3px;" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBox(item.RoomCategory, new { type = "text", #id = "roomCat", #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<p>
<input type="button" class="btn btn-info btn-add" name="PaymentDetails" id="PaymentDetails_btn" value="Add" data-url="#Url.Action("PaymentDetails", "EVoucher")" />
</p>
</div>
}
</div>
</div>
I can save the value to database when the user clicks on add button by using Ajax call. But How can I change the foreach loop value according the relevant iteration?
Any help will really appreciate. Thanks
Update - #Liam, I want to change #item.RoomType, #item.RoomCategory according to the foreach loop value. But I dont want to display all the inputs at one time. For ex if I have count 20, I only want to display one at a time. not all 20.

Categories