dynamically add 'add button' inside for loop - c#

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.

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!

Update a Multiple divs via ajax

I have a form for adding Books in a database,
I Have a modal window in my form to create a Publisher, if the specified format doesn't exist in Publisher Dropdown, I Create my Modal in a partial view for add Publisher,
this is my view:
#model WebApplication3.Models.BookModel
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="CustomerList"></div>
<h2>Create New Book</h2>
<label class="text-#ViewBag.ClassName">
#ViewBag.Message
</label>
#using (Html.BeginForm("CreateBook", "Book", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.TitleID, "TitleID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("TitleID", null, "Select a Title", htmlAttributes: new { #class = "form-control" })
#Html.ActionLink("Add New", "Create", "Title")
#Html.ValidationMessageFor(model => model.TitleID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FormatID, "FormatID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("FormatID", null, "Select a Format", htmlAttributes: new { #class = "form-control" })
<a href="" class="" data-toggle="modal" data-target="#FormatModal">
Add New
</a>
#Html.ValidationMessageFor(model => model.FormatID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ISBN, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ISBN, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ISBN, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Quantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Quantity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
}
<div class="modal fade" id="PublisherModal" tabindex="-1" role="dialog" aria-labelledby="publisherModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
#Html.Partial("_Publisher")
</div>
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryajax")
}
and this is my Publisher partial view:
#model WebApplication3.Models.PublisherModel
#using (Ajax.BeginForm("CreatePublisher", "Book", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "publisherForm", InsertionMode = InsertionMode.ReplaceWith }))
{
<div id="publisherForm">
<div class="modal-header">
<h5 class="modal-title" id="publisherModalLongTitle">Create New Publisher</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
<span class="text-#ViewBag.ClassName">
#ViewBag.Message
</span>
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Value, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Value, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Value, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
#Html.ActionLink("Manage", "Index", "Publisher", new { area = "" }, new { #class = "btn btn-link" })
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
}
and this is my controller
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult CreatePublisher([Bind(Include = "ID,Value,Description")] PublisherModel publisherModel)
{
ViewBag.TitleID = new SelectList(repoTitle.GetModels(), "ID", "Title");
ViewBag.FormatID = new SelectList(repoFormat.GetModels(), "ID", "Value");
PublisherModel publisher = repoPublisher.GetModels().FirstOrDefault(x => x.Value == publisherModel.Value);
if (publisher == null)
{
if (ModelState.IsValid)
{
repoPublisher.Insert(publisherModel);
ViewBag.PublisherID = new SelectList(repoPublisher.GetModels(), "ID", "Value", publisherModel.ID);
ViewBag.Message = $"Publisher \"{publisherModel.Value}\" Added Successfully";
ViewBag.ClassName = "success";
return PartialView("_Publisher");
}
}
else
{
ViewBag.Message = $"Publisher \"{publisherModel.Value}\" Already Exsisted";
ViewBag.ClassName = "danger";
}
ViewBag.PublisherID = new SelectList(repoPublisher.GetModels(), "ID", "Value");
return PartialView("_Publisher",publisherModel);
}
How Can change to my code that if a new Publisher inserted to Database, the Publisher dropdown refresh and select newly inserted data as a selected item?
About question
I can't run your code locally.
These operations can be implemented through JS.
I can show my tools.
This is the function gif:
Solution:
Select and add options as a whole.
// index.cshtml
<div>
#await Component.InvokeAsync("AutoAddListValue")
</div>
//Component
#model List<string>
<h3>Default page</h3>
<div>
<div>
<p>Lists</p>
<select name="select" class="" id="ComponentSelectId" onclick="ComponentSelectClick()">
<option id="ComponentOptionId" style="width:auto">ComponentTest</option>
#if (Model.Count != 0)
{
int count = Model.Count();
for (int item = 0; item < count; item++)
{
<option id="option">#Model[item].ToString()</option>
}
}
</select>
</div>
<div>
<input id="ComponentTestJsInput" class="d-none" value="132323" type="text" />
<input id="ComponentBtnDisplay" value="Add" type="button" class="btn btn-primary" onclick="ComponentBtnDisplayClick()">
<input id="ComponentBtnAdd" value="Add" type="button" class="btn btn-primary d-none" onclick="ComponentBtnAddClick()">
</div>
</div>
Bind data for components.
public class AutoAddListValueViewComponent : ViewComponent
{
private readonly SchoolContext _context;
public AutoAddListValueViewComponent(SchoolContext context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync(
int maxPriority, bool isDone)
{
string MyView = "Default";
var items = await GetListAsync();
return View(MyView, items);
}
public async Task<List<string>> GetListAsync()
{
return await _context.Test.Select(o => o.Name).ToListAsync();
}
}
Using JS code to realize page interaction.
var ComponentBtnDisplayClick = function () {
$('#ComponentBtnAdd').removeClass("d-none");
$('#ComponentTestJsInput').removeClass("d-none");
$('#ComponentBtnDisplay').addClass("d-none");
}
var ComponentBtnAddClick = function () {
//alert("666666");
$('#ComponentBtnAdd').addClass("d-none");
$('#ComponentTestJsInput').addClass("d-none");
$('#ComponentBtnDisplay').removeClass("d-none");
inputVal = $('#ComponentTestJsInput').val();
//alert(inputVal);
$.ajax({
url: '/Test/SaveInputValue',
data: {
name: inputVal
},
type: 'post',
async: true,
cache: false,
success: function (data) {
//alert(data.code);
var option = "<option id='ComponentOptionId'>";
option += inputVal;
option += "</option>";
$("#ComponentSelectId").append(option);
var obj = document.getElementById("ComponentSelectId");
obj[obj.length - 1].selected = true;
},
error: function () {
alert('fail');
}
});
}
Other code
Source Code

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.

create new record via multiple model in one view

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

Enter Key function is not working correctly in MVC5?

Hi I want to navigate from one field to another field by pressing enter Key in MVC5. So i used Enter Key function code.The code is mention below.
My View
<form>
<fieldset>
<legend></legend>
<div class="col-sm-3">
<div class="form-group">
<span style="color: #f00">*</span>
#Html.Label("Customer Name", new { #class = "control-label" })
#Html.ValidationMessageFor(model => model.CustomerName)
#Html.TextBoxFor(model => model.CustomerName, new { #class = "form-control required", type = "text" })
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#Html.LabelFor(model => model.Alias, new { #class = "control-label" })
#Html.DropDownList("SalutationID", null, "Select", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Alias)
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<span style="color: #f00">*</span>
#Html.Label("Customer Type", new { #class = "control-label" })
#Html.DropDownList("CustomerTypeID", null, "Select", new { #class = "form-control required" })
</div>
</div>
<hr style="width:100% ; align-self:baseline">
<h3 style="color: #0000FF">Address</h3>
<div class="col-sm-3">
<div class="form-group">
<span style="color: #f00">*</span>
#Html.Label("Address Type", new { #class = "control-label" })
#Html.DropDownList("AddressTypeID", null, "Select", new { #class = "form-control required" })
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<span style="color: #f00">*</span>
#Html.LabelFor(model => model.Street, new { #class = "control-label" })
#Html.TextBoxFor(model => model.Street, new { #class = "form-control", type = "text required" })
#Html.ValidationMessageFor(model => model.Street)
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#Html.LabelFor(model => model.Location, new { #class = "control-label" })
#Html.TextBoxFor(model => model.Location, new { #class = "form-control", type = "text " })
#Html.ValidationMessageFor(model => model.Location)
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#Html.LabelFor(model => model.Place, new { #class = "control-label" })
#Html.TextBoxFor(model => model.Place, new { #class = "form-control", type = "text" })
#Html.ValidationMessageFor(model => model.Place)
</div>
</div>
</fieldset>
</form>
My Jquery code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
</script>
<script type="text/javascript">
$("form:not(.filter) :visible:enabled:first").focus();
$('form > div').keypress(function(e) {
debugger;
if (e.keyCode == 13) {
e.preventDefault();
if ($(this).next().length > 0) {
$(this).next().children('div').children(":not(label)").focus();
} else {
$("form:not(.filter) :visible:enabled:first").focus();
}
}
});
I tried this code. In this code it showing plugin error which is near to below plugin.
<script type="text/javascript" src="./javascript.js"></script>
I tried many ways to remove this plugin error but no use. please any one help me to resolve this issue.
Advance Thanks..
Looks like the jQuery is not initialized. Use it like this:
$(function () {
$("form:not(.filter) :visible:enabled:first").focus();
$('form > div').keypress(function(e) {
debugger;
if (e.keyCode == 13) {
e.preventDefault();
if ($(this).next().length > 0) {
$(this).next().children('div').children(":not(label)").focus();
} else {
$("form:not(.filter) :visible:enabled:first").focus();
}
}
});
});
Notice that your entire javascript code should be encapsulated within
$(function ()
{
//Your javascript goes here
});
The other problem I see is that your local javascript file "javascript.js" path is not correct. You will have to correct that to load your javascript file and get rid of the 404 errors. Same goes with the img.jpg file as well.

Categories