In the contact creation I want to assign a customer or supplier from a dropdown - validation

I have two problems.
1. Problem: When I add my selection to the razor page all required fields validation from the model do not work anymore.
Validation from model without selection
No Validation when I add my selection
When dropdown are in the Razor html no validation works and it crashes with NULL Values which I want to prevent. Like it is without select options.
Why is that?
2. Problem: When I select a customer from my drop down (CustomerDropDown.CusId) I would like to fill the ID into my ID field of contacts (contacts.CustomerId). How can I reach the selected value from dropdown and post it to my contact contacts.CustomerId?
== c# code ==
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Rendering;
using WorkCollaboration.Data;
using WorkCollaboration.Models;
namespace WorkCollaboration.Pages.Contacts
{
public class CreateModel : PageModel
{
private readonly WorkCollaboration.Data.WorkCollaborationContext _context;
public CreateModel(WorkCollaboration.Data.WorkCollaborationContext context)
{
_context = context;
}
public async Task<IActionResult> OnGetAsync()
{
CustomerDropDownDisp = await _context.CustomerDropDown.ToListAsync(); // Added for DropDown
SupplierDropDownDisp = await _context.SupplierDropDown.ToListAsync(); // Added for DropDown
return Page();
}
[BindProperty]
public Contact Contact { get; set; }
public IEnumerable<CustomerDropDown> CustomerDropDownDisp { get; set; }
public IEnumerable<SupplierDropDown> SupplierDropDownDisp { get; set; }
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Contact.Add(Contact);
await _context.SaveChangesAsync();
return RedirectToPage("/ContactsOverview/Index");
}
}
}
== Razor Page Code ==
#page
#using WorkCollaboration.Models
#model WorkCollaboration.Pages.Contacts.CreateModel
#{
ViewData["Title"] = "Create";
ViewData["RandomId"] = Guid.NewGuid().GetHashCode();
}
<h1>Create</h1>
<h4>Contact</h4>
<p>
<a asp-page="/ContactsOverview/Index">Back to Index</a>
</p>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Contact.ContactId" class="control-label"></label>
<input asp-for="Contact.ContactId" value='#ViewData["RandomId"]' readonly="readonly" class="form-control" />
<span asp-validation-for="Contact.ContactId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.LastName" class="control-label"></label>
<input asp-for="Contact.LastName" class="form-control" />
<span asp-validation-for="Contact.LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.FirstName" class="control-label"></label>
<input asp-for="Contact.FirstName" class="form-control" />
<span asp-validation-for="Contact.FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.CustomerId" class="control-label"></label>
</div>
<select id="CusId" asp-for="CustomerDropDownDisp" asp-items="#(new SelectList(Model.CustomerDropDownDisp,"CusId","CusName"))">
<option value="">--Choose Customer--</option>
<option value="1" selected>None</option>>
</select>
<div class="form-group">
<input asp-for="Contact.CustomerId" class="form-control" />
<span asp-validation-for="Contact.CustomerId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.SupplierId" class="control-label"></label>
</div>
<select id="SupId" asp-for="SupplierDropDownDisp" asp-items="#(new SelectList(Model.SupplierDropDownDisp,"SupId","SupName"))">
<option value="">--Choose Supplier--</option>
<option value="1" selected>None</option>>
</select>
<div class="form-group">
<input asp-for="Contact.SupplierId" class="form-control" />
<span asp-validation-for="Contact.SupplierId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.PrivateStreet" class="control-label"></label>
<input asp-for="Contact.PrivateStreet" class="form-control" />
<span asp-validation-for="Contact.PrivateStreet" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.PrivateStreetNo" class="control-label"></label>
<input asp-for="Contact.PrivateStreetNo" class="form-control" />
<span asp-validation-for="Contact.PrivateStreetNo" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.PrivateStreetAdditionalInfo" class="control-label"></label>
<input asp-for="Contact.PrivateStreetAdditionalInfo" class="form-control" />
<span asp-validation-for="Contact.PrivateStreetAdditionalInfo" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.PrivateZip" class="control-label"></label>
<input asp-for="Contact.PrivateZip" class="form-control" />
<span asp-validation-for="Contact.PrivateZip" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.PrivateTown" class="control-label"></label>
<input asp-for="Contact.PrivateTown" class="form-control" />
<span asp-validation-for="Contact.PrivateTown" class="text-danger"></span>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Contact.PrivateCountry, htmlAttributes: new { #class = "form-group" })
<div class="form-group">
#Html.DropDownListFor(model => model.Contact.PrivateCountry, new List<SelectListItem>
{
new SelectListItem {Text = "CH", Value = "CH", Selected = true },
new SelectListItem {Text = "D", Value = "D" },
new SelectListItem {Text = "FL", Value = "FL" },
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Contact.PrivateCountry, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label asp-for="Contact.PrivatePhone" class="control-label"></label>
<input asp-for="Contact.PrivatePhone" class="form-control" />
<span asp-validation-for="Contact.PrivatePhone" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.BusinessPhone" class="control-label"></label>
<input asp-for="Contact.BusinessPhone" class="form-control" />
<span asp-validation-for="Contact.BusinessPhone" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.MobilePhone" class="control-label"></label>
<input asp-for="Contact.MobilePhone" class="form-control" />
<span asp-validation-for="Contact.MobilePhone" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.Mail" class="control-label"></label>
<input asp-for="Contact.Mail" class="form-control" />
<span asp-validation-for="Contact.Mail" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
Back to List
</div>
</form>
</div>
</div>
Thank you for your help on how to get selected value (dropdown) to the corresponding contacts Id field.

Here is a demo:
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Contact.ContactId" class="control-label"></label>
<input asp-for="Contact.ContactId" value='#ViewData["RandomId"]' readonly="readonly" class="form-control" />
<span asp-validation-for="Contact.ContactId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.LastName" class="control-label"></label>
<input asp-for="Contact.LastName" class="form-control" />
<span asp-validation-for="Contact.LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.FirstName" class="control-label"></label>
<input asp-for="Contact.FirstName" class="form-control" />
<span asp-validation-for="Contact.FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.CustomerId" class="control-label"></label>
</div>
<select id="CusId" asp-for="CustomerDropDownDisp" asp-items="#(new SelectList(Model.CustomerDropDownDisp,"CusId","CusName"))">
<option value="">--Choose Customer--</option>
<option value="1" selected>None</option>>
</select>
<div class="form-group">
<input asp-for="Contact.CustomerId" class="form-control" />
<span asp-validation-for="Contact.CustomerId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.SupplierId" class="control-label"></label>
</div>
<select id="SupId" asp-for="SupplierDropDownDisp" asp-items="#(new SelectList(Model.SupplierDropDownDisp,"SupId","SupName"))">
<option value="">--Choose Supplier--</option>
<option value="1" selected>None</option>>
</select>
<div class="form-group">
<input asp-for="Contact.SupplierId" class="form-control" />
<span asp-validation-for="Contact.SupplierId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.PrivateStreet" class="control-label"></label>
<input asp-for="Contact.PrivateStreet" class="form-control" />
<span asp-validation-for="Contact.PrivateStreet" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.PrivateStreetNo" class="control-label"></label>
<input asp-for="Contact.PrivateStreetNo" class="form-control" />
<span asp-validation-for="Contact.PrivateStreetNo" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.PrivateStreetAdditionalInfo" class="control-label"></label>
<input asp-for="Contact.PrivateStreetAdditionalInfo" class="form-control" />
<span asp-validation-for="Contact.PrivateStreetAdditionalInfo" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.PrivateZip" class="control-label"></label>
<input asp-for="Contact.PrivateZip" class="form-control" />
<span asp-validation-for="Contact.PrivateZip" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.PrivateTown" class="control-label"></label>
<input asp-for="Contact.PrivateTown" class="form-control" />
<span asp-validation-for="Contact.PrivateTown" class="text-danger"></span>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Contact.PrivateCountry, htmlAttributes: new { #class = "form-group" })
<div class="form-group">
#Html.DropDownListFor(model => model.Contact.PrivateCountry, new List<SelectListItem>
{
new SelectListItem {Text = "CH", Value = "CH", Selected = true },
new SelectListItem {Text = "D", Value = "D" },
new SelectListItem {Text = "FL", Value = "FL" },
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Contact.PrivateCountry, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label asp-for="Contact.PrivatePhone" class="control-label"></label>
<input asp-for="Contact.PrivatePhone" class="form-control" />
<span asp-validation-for="Contact.PrivatePhone" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.BusinessPhone" class="control-label"></label>
<input asp-for="Contact.BusinessPhone" class="form-control" />
<span asp-validation-for="Contact.BusinessPhone" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.MobilePhone" class="control-label"></label>
<input asp-for="Contact.MobilePhone" class="form-control" />
<span asp-validation-for="Contact.MobilePhone" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Contact.Mail" class="control-label"></label>
<input asp-for="Contact.Mail" class="form-control" />
<span asp-validation-for="Contact.Mail" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
Back to List
</div>
</form>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script>
$("#CusId").on("change", function () {
$("#Contact_CustomerId").val($("#SupId").val());
});
$("#SupId").on("change", function () {
$("#Contact_SupplierId").val($("#SupId").val());
});
</script>
result:

Related

How to display a null date in a Net Core view

I have a model with date type properties that can be null
[Display(Name = "Vig. Conf.")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true, NullDisplayText = "-")]
public DateTime? VigenciaConfeccion
{
get => _vigenciaConfeccion;
set
{
if (_vigenciaConfeccion != value)
{
_vigenciaConfeccion = value;
OnPropertyChanged(nameof(VigenciaConfeccion));
}
}
}
This is the view that where the error is generated in the format of the three date labels.
#model WebProcesoTela.Models.VDiagramaDetailModel
#{
// ViewData["Title"] = "Details";
Layout = null;
}
<div class = "container-fluid">
<h2>Detalle del renglón</h2>
<hr/>
<div class="row">
<div class="col-sm-2">
<label asp-for="DiagramaId" class="control-label">#Html.DisplayNameFor(model => model.DiagramaId)</label>
<input asp-for="DiagramaId" class="form-control text-center" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="DiagramaDetailId" class="control-label">#Html.DisplayNameFor(model => model.DiagramaDetailId)</label>
<input asp-for="DiagramaDetailId" class="form-control text-center" readonly disabled/>
</div>
<div class="col-sm-4">
<label asp-for="CompradorName" class="control-label">#Html.DisplayNameFor(model => model.CompradorName)</label>
<input asp-for="CompradorName" class="form-control" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="ClaveLinea" class="control-label">#Html.DisplayNameFor(model => model.ClaveLinea)</label>
<input asp-for="ClaveLinea" class="form-control" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="VigenciaBonmoro" class="control-label">#Html.DisplayNameFor(model => model.VigenciaBonmoro)</label>
<input type="date" asp-for="VigenciaBonmoro" asp-format="{0:yyyy-MM-dd}" class="form-control" readonly disabled/>
</div>
</div>
<div class="row">
<div class="col-sm-2">
<label asp-for="VigenciaBannio" class="control-label">#Html.DisplayNameFor(model => model.VigenciaBannio)</label>
<input type="date" asp-for="VigenciaBannio" asp-format="{0:yyyy-MM-dd}" class="form-control" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="VigenciaConfeccion" class="control-label">#Html.DisplayNameFor(model => model.VigenciaConfeccion)</label>
<input type="date" asp-for="VigenciaConfeccion" asp-format="{0:yyyy-MM-dd}" class="form-control" readonly disabled/>
</div>
<div class="col-sm-8">
<label asp-for="ComentariosTejido" class="control-label">#Html.DisplayNameFor(model => model.ComentariosTejido)</label>
<input asp-for="ComentariosTejido" class="form-control" readonly disabled/>
</div>
</div>
<div class="row">
<div class="col-sm-2">
<label asp-for="FolioTejido" class="control-label">#Html.DisplayNameFor(model => model.FolioTejido)</label>
<input asp-for="FolioTejido" class="form-control" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="FolioTejedor" class="control-label">#Html.DisplayNameFor(model => model.FolioTejedor)</label>
<input asp-for="FolioTejedor" class="form-control" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="Bannio" class="control-label">#Html.DisplayNameFor(model => model.Bannio)</label>
<input asp-for="Bannio" class="form-control" readonly disabled/>
</div>
<div class="col-sm-3">
<label asp-for="TejedorName" class="control-label">#Html.DisplayNameFor(model => model.TejedorName)</label>
<input asp-for="TejedorName" class="form-control" readonly disabled/>
</div>
<div class="col-sm-3">
<label asp-for="AcabadorName" class="control-label">#Html.DisplayNameFor(model => model.AcabadorName)</label>
<input asp-for="AcabadorName" class="form-control" readonly disabled/>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<label asp-for="DeptoCategoriaName" class="control-label">#Html.DisplayNameFor(model => model.DeptoCategoriaName)</label>
<input asp-for="DeptoCategoriaName" class="form-control" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="PedidoInterno" class="control-label">#Html.DisplayNameFor(model => model.PedidoInterno)</label>
<input asp-for="PedidoInterno" class="form-control" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="ModeloId" class="control-label">#Html.DisplayNameFor(model => model.ModeloId)</label>
<input asp-for="ModeloId" class="form-control" readonly disabled/>
</div>
<div class="col-sm-4">
<label asp-for="PiezaName" class="control-label">#Html.DisplayNameFor(model => model.PiezaName)</label>
<input asp-for="PiezaName" class="form-control" readonly disabled/>
</div>
</div>
<div class="row">
<div class="col-sm-2">
<label asp-for="Variante" class="control-label">#Html.DisplayNameFor(model => model.Variante)</label>
<input asp-for="Variante" class="form-control text-center" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="TipoFondoName" class="control-label">#Html.DisplayNameFor(model => model.TipoFondoName)</label>
<input asp-for="TipoFondoName" class="form-control" readonly disabled/>
</div>
<div class="col-sm-6">
<label asp-for="ColorName" class="control-label">#Html.DisplayNameFor(model => model.ColorName)</label>
<input asp-for="ColorName" class="form-control" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="CodigoColorProv" class="control-label">#Html.DisplayNameFor(model => model.CodigoColorProv)</label>
<input asp-for="CodigoColorProv" class="form-control" readonly disabled/>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<label asp-for="TipoCuelloName" class="control-label">#Html.DisplayNameFor(model => model.TipoCuelloName)</label>
<input asp-for="TipoCuelloName" class="form-control" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="GpoCodigoTallaName" class="control-label">#Html.DisplayNameFor(model => model.GpoCodigoTallaName)</label>
<input asp-for="GpoCodigoTallaName" class="form-control" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="TotalPiezas" class="control-label">#Html.DisplayNameFor(model => model.TotalPiezas)</label>
<input type="text" asp-for="TotalPiezas" class="form-control" readonly disabled/>
</div>
<div class="col-sm-5">
<label asp-for="TelaNameDD" class="control-label">#Html.DisplayNameFor(model => model.TelaNameDD)</label>
<input asp-for="TelaNameDD" class="form-control" readonly disabled/>
</div>
</div>
<div class="row">
<div class="col-sm-2">
<label asp-for="EstampadoId" class="control-label">#Html.DisplayNameFor(model => model.EstampadoId)</label>
<input asp-for="EstampadoId" class="form-control" readonly disabled/>
</div>
<div class="col-sm-3">
<label asp-for="EstampadoName" class="control-label">#Html.DisplayNameFor(model => model.EstampadoName)</label>
<input asp-for="EstampadoName" class="form-control" readonly disabled/>
</div>
<div class="col-sm-7">
<label asp-for="EstampadoEspecificacion" class="control-label">#Html.DisplayNameFor(model => model.EstampadoEspecificacion)</label>
<input asp-for="EstampadoEspecificacion" class="form-control" readonly disabled/>
</div>
</div>
<div class="row">
<div class="col-sm-2">
<label asp-for="CodigoEstampado" class="control-label">#Html.DisplayNameFor(model => model.CodigoEstampado)</label>
<input asp-for="CodigoEstampado" class="form-control" readonly disabled/>
</div>
<div class="col-sm-3">
<label asp-for="HilanderoName" class="control-label">#Html.DisplayNameFor(model => model.HilanderoName)</label>
<input asp-for="HilanderoName" class="form-control" readonly disabled/>
</div>
<div class="col-sm-3">
<label asp-for="HiloNameDD" class="control-label">#Html.DisplayNameFor(model => model.HiloNameDD)</label>
<input asp-for="HiloNameDD" class="form-control" readonly disabled/>
</div>
<div class="col-sm-4">
<label asp-for="HiloComposicion" class="control-label">#Html.DisplayNameFor(model => model.HiloComposicion)</label>
<input asp-for="HiloComposicion" class="form-control" readonly disabled/>
</div>
</div>
<div class="row">
<div class="col-sm-2">
<label asp-for="HiloGrsMt2" class="control-label">#Html.DisplayNameFor(model => model.HiloGrsMt2)</label>
<input asp-for="HiloGrsMt2" class="form-control" readonly disabled/>
</div>
<div class="col-sm-3">
<label asp-for="TejidoEspecificacion" class="control-label">#Html.DisplayNameFor(model => model.TejidoEspecificacion)</label>
<input asp-for="TejidoEspecificacion" class="form-control" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="TelaAcabadoName" class="control-label">#Html.DisplayNameFor(model => model.TelaAcabadoName)</label>
<input asp-for="TelaAcabadoName" class="form-control" readonly disabled/>
</div>
<div class="col-sm-5">
<label asp-for="Nota" class="control-label">#Html.DisplayNameFor(model => model.Nota)</label>
<input asp-for="Nota" class="form-control" readonly disabled/>
</div>
</div>
<div class="row">
<div class="col-sm-2 offset-sm-6">
<label asp-for="TotalTelaKilos" class="control-label">#Html.DisplayNameFor(model => model.TotalTelaKilos)</label>
<input asp-for="TotalTelaKilos" class="form-control" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="TotalTelaMetros" class="control-label">#Html.DisplayNameFor(model => model.TotalTelaMetros)</label>
<input asp-for="TotalTelaMetros" class="form-control" readonly disabled/>
</div>
<div class="col-sm-2">
<label asp-for="TotalTelaKgsSinMerma" class="control-label">#Html.DisplayNameFor(model => model.TotalTelaKgsSinMerma)</label>
<input asp-for="TotalTelaKgsSinMerma" class="form-control" readonly disabled/>
</div>
</div>
<div class="row"></div>
</div>
<hr />
<div class="form-group">
<!-- Barra de Botones Details Modal -Regresar- -->
<partial name="~/Views/Shared/Controls/_BtnsDetailsModal.cshtml"/>
</div>
When I load the view and the date is null, the "Input tag" shows "dd/MM/yyyy"
The editor asks me to put more details, but I don't know what else to put, since the problem is very simple.
The "input" tags display "dd/mm/yyyy" when the field is null.
What can I do so that it doesn't show me anything?
I think you can try to change the style of the date input. Using onfocu and onblur action
<div class="form-group">
<label asp-for="VigenciaConfeccion" class="control-label"></label>
<input asp-for="VigenciaConfeccion" class="form-control" onfocus="(this.style.color='#000')" onblur="if(!this.value)this.style.color='transparent'" />
<span asp-validation-for="VigenciaConfeccion" class="text-danger"></span>
</div>
#section Scripts{
<script>
$("#VigenciaConfeccion").focus();
$("#VigenciaConfeccion").blur();
</script>
}

How to solve erroe 428C9 in ASP.NET Core MVC?

I made a new function for my website.It can do the job like save as.
And it can work will.
But when I create a new project, it suddenly can't work,and show the error 428C9.
What should I do? Can someone give me advice?
It is .cshtml
<div class="row">
<div class="col-xl-10">
<form asp-action="Saveas">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="IpAddress" class="control-label"></label>
<input asp-for="IpAddress" class="form-control" />
<span asp-validation-for="IpAddress" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Protocol" class="control-label"></label>
<input asp-for="Protocol" class="form-control" />
<span asp-validation-for="Protocol" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ToolHostPort" class="control-label"></label>
<input asp-for="ToolHostPort" class="form-control" />
<span asp-validation-for="ToolHostPort" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ToolSvid" class="control-label"></label>
<input asp-for="ToolSvid" class="form-control" />
<span asp-validation-for="ToolSvid" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Pid" class="control-label"></label>
<input asp-for="Pid" class="form-control" />
<span asp-validation-for="Pid" class="text-danger"></span>
</div>
<input type="hidden" asp-for="Pid" />
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
It is controller
public async Task<IActionResult> Saveas(int? id)
{
if (id == null)
{
return NotFound();
}
var gatewaySettingCloud = await _context.GatewaySettingClouds.FindAsync(id);
if (gatewaySettingCloud == null)
{
return NotFound();
}
return View(gatewaySettingCloud);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Saveas([Bind("Ipaddress,Protocol,Toolhostport,Toolsvid,Pid")] GatewaySettingCloud gatewaySettingCloud)
{
if (ModelState.IsValid)
{
_context.Add(gatewaySettingCloud);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(gatewaySettingCloud);
}
I find the database does not accept from applications, so I create a new column replace original column which one can't accept data from applications.Then I can insert the data successful!!
Helper:Karl-Johan Sjögren、Tiny Wang

How to send some data and image from AJAX to Controller in Laravel?

I'm a freshmen in the office and I was assigned by my boss to fix the code of the website that the developer is not in the company anymore. He used mostly AJAX to do things which I'm not used to it. I rarely use AJAX in my project, so I'm very very new about this.
From the old code, I'm trying to send an image with some data from an input form. I can console.log(form_data) to see its values, but I don't know why the content of image cannot be sent to Controller. It's getting 'null' and I can't store it.
Here is the code in input form
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">{{$head}}</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="input-form" class="needs-validation" novalidate method="POST" enctype="multipart/form-data" name="input-form">
{{ csrf_field() }}
<div class="form-horizontal">
<div class="form-group required">
<label class="col-sm-12 control-label" for="thai_name">{{trans('home.thai_name')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="thai_name" name="thai_name" value="{{isset($user) ? $user->thai_name : ''}}" required/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="eng_name">{{trans('home.eng_name')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="eng_name" name="eng_name" value="{{isset($user) ? $user->eng_name : ''}}" required/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="email">{{trans('home.email')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="email" name="email" value="{{isset($user) ? $user->email : ''}}" required/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="password">{{trans('home.password')}}</label>
<div class="col-sm-12">
<input type="password" id="password" class="form-control" required/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="password_confirmation">{{trans('home.password_confirmation')}}</label>
<div class="col-sm-12">
<input type="password" id="password_confirmation" class="form-control" required/>
</div>
</div>
<div class="form-group col-sm-12">
<a class="btn-link" id="message" style="text-align: center;"></a>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="phone">{{trans('home.phone')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="phone" name="phone" value="{{isset($user) ? $user->telephone : ''}}" required/>
</div>
</div>
<div class="form-group">
<label class="col-sm-12 control-label" for="fax">{{trans('home.fax')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="fax" name="fax" value="{{isset($user) ? $user->fax : ''}}"/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label">{{trans('home.system_role')}}</label>
<div class="col-sm-12">
<div class="form-check form-check-inline">
<input class="form-check-input role" type="radio" id="admin" name="role" value="1"
{{isset($user) && $user->system_role_id == 1 ? 'checked' : ''}} required>
<label class="form-check-label" for="admin">ผู้ดูแลระบบ</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input role" type="radio" id="content_admin" name="role" value="2"
{{isset($user) && $user->system_role_id == 2 ? 'checked' : ''}} required>
<label class="form-check-label" for="content_admin">ผู้ดูแลข้อมูล</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input role" type="radio" id="user" name="role" value="3"
{{isset($user) && $user->system_role_id == 3 ? 'checked' : ''}} required>
<label class="form-check-label" for="user">ผู้ใช้งาน</label>
</div>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label">{{trans('home.faction')}}</label>
<div class="col-sm-12">
<select id="faction" class="form-control">
#foreach($factions as $faction)
<option value="{{$faction->id}}" {{isset($user) && $user->faction_id == $faction->id ? 'selected' : ''}}>
{{trans('home.'.$faction->name)}}
</option>>
#endforeach
</select>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label">{{trans('home.position')}}</label>
<div class="col-sm-12">
<select id="position" class="form-control">
#foreach($positions as $position)
<option value="{{$position->id}}" {{isset($user) && $user->position_id == $position->id ? 'selected' : ''}}>
{{trans('home.'.$position->name)}}
</option>>
#endforeach
</select>
</div>
</div>
<div class="form-group required">
<div class="col-sm-12">
<label class="control-label" for="photo">รูปถ่าย</label>
<input type="file" class="form-control-file" id="photo" name="photo" accept="image/*" required/>
</div>
</div>
<div class="form-group">
<label class="col-sm-12 control-label">{{trans('home.acting')}} / {{trans('home.past')}}</label>
<div class="col-sm-12">
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="acting" name="acting" {{isset($user) && $user->is_acting ? 'checked' : ''}}>
<label class="form-check-label" for="acting">{{trans('home.acting')}}</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="past" name="past" {{isset($user) && $user->is_past ? 'checked' : ''}}>
<label class="form-check-label" for="past">{{trans('home.past')}}</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-12" for="start">{{trans('home.start')}}</label>
<div class="col-sm-12">
<div class="input-group" id="start" name="start">
<input type="text" class="form-control" readonly="readonly"/>
<div class="input-group-append">
<span class="input-group-text input-group-addon">
<span class="fa fa-calendar"></span>
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-12" for="end">{{trans('home.end')}}</label>
<div class="col-sm-12">
<div class="input-group" id="end" name="end">
<input type="text" class="form-control" readonly="readonly"/>
<div class="input-group-append">
<span class="input-group-text input-group-addon">
<span class="fa fa-calendar"></span>
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row col-sm-12 text-center">
<input type="button" class="btn btn-default" value="{{trans('home.save')}}"
onclick="{{$func}}"
/>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#start').datetimepicker({
sideBySide: true,
locale: 'th',
format: 'YYYY-MM-DD',
ignoreReadonly: true,
defaultDate: "{{isset($user) ? $user->start : ''}}"
});
$('#end').datetimepicker({
sideBySide: true,
locale: 'th',
format: 'YYYY-MM-DD',
ignoreReadonly: true,
defaultDate: "{{isset($user) ? $user->end : ''}}"
});
$('#password, #password_confirmation').on('keyup', function () {
if ( $('#password').val() == $('#password_confirmation').val() ) {
if ( $('#password').val() != '') {
$('#message').html('{{trans("home.password_match")}}').css('color', 'green');
} else {
$('#message').html('{{trans("home.password_null")}}').css('color', 'red');
$('#password').removeClass('valid').addClass('invalid');
$('#password_confirmation').removeClass('valid').addClass('invalid');
}
} else {
$('#message').html('{{trans("home.password_mismatch")}}').css('color', 'red');
$('#password').removeClass('valid').addClass('invalid');
$('#password_confirmation').removeClass('valid').addClass('invalid');
}
});
});
</script>
Here is the code in user.js where I'm using AJAX to send form_data contains image and some data
function addUser() {
var validate = validateUser("add");
if (validate.error == '') {
$('#modal1').modal({backdrop: "static"});
var form_data = {
thai_name: validate.thai_name,
eng_name: validate.eng_name,
email: validate.email,
password: validate.password,
password_confirmation: validate.password_confirmation,
telephone: $('#phone').val(),
fax: $('#fax').val(),
system_role_id: $('input[name=role]:checked').val(),
faction_id: $('#faction').val(),
position_id: $('#position').val(),
photo: $('#photo').val(),
photo_file: $('#photo').prop("files")[0],
is_acting: 0,
is_past: 0,
start: $('#start').data('date'),
end: $('#end').data('date'),
};
if ($('#acting').is(':checked')) {
form_data.is_acting = 1;
}
if ($('#past').is(':checked')) {
form_data.is_past = 1;
}
console.log(form_data);
$.ajax({
type: "post",
enctype: "multipart/form-data",
url: baseurl + "/admin/user/add",
data: form_data,
processData: false,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function () {
$('#input-area').modal('hide');
listUser();
}
});
}
}
Here is some code in my controller
public function addUser(Request $request) {
$user = new User();
$user->thai_name = request()->thai_name;
$user->eng_name = request()->eng_name;
$user->email = request()->email;
$user->password = Hash::make(request()->password);
$user->telephone = request()->telephone;
$user->fax = request()->fax;
$user->system_role_id = request()->system_role_id;
$user->faction_id = request()->faction_id;
$user->position_id = request()->position_id;
// Store Profile Photo
$filename = "profile-photo-" . time() . "-name-" . basename(request()->photo);
request()->file('photo_file')->storeAs('', $filename, 'images');
$user->photo = $filename;
$user->is_acting = request()->is_acting;
$user->is_past = request()->is_past;
$user->start = request()->start;
$user->end = request()->end;
$user->save();
}
Which part I did wrong? Any ideas?
Please help me figure this out.
Thank you in advanced.

ASP.NET Core MVC app : I want to show the same view after submit and render the same data but having problems

I am new to ASP.NET Core MVC but I do have some experience working with ASP.NET webforms. I am creating an ASP.NET Core MVC project for practice in this I have a controller which has [http post] Create and Http Get Create action methods.
When user is on the Create page after entering the data user can click the submit button and once the data is saved, the view for http post Create() is render (reloading same view) and I am trying to show the data that user has filled prior to submit but data is not binding to the input controls. I am passing the same model to the view which was sent to be saved. During the debug and I am able to see the expected value under the Locals window in Visual Studio.
I want to understand what I am doing wrong or what changes I should be doing in order to work. If I need to take the different approach then why this the approach (mentioned below in code) I am taking is not correct?
Below is the code and explanation in the comments.
[HttpGet]
public async Task<IActionResult> Create()
{
// I am creating a viewModel object because wanted to include the logic for List<users> for dropdown.
var createView = await _chloramine.ChloramineSaveViewModel();
return View(createView);
}
[HttpPost]
// At page submit this Action method is called and data is saved.
public async Task<IActionResult> Create(ChloramineLogEditSaveViewModel clEditSaveViewModel)
{
_chloramine.CreateChloramineLog(clEditSaveViewModel);
// After data is saved I am adding a user list to the model because I was getting Object null error.
clEditSaveViewModel.User = await _chloramine.GetUser();
// Passing the same model object which was received in order to show what was filled or selected by the user.
return View(clEditSaveViewModel);
}
Below is the Create view html.
#model EquipmentMVC.Models.ChloramineLogEditSaveViewModel
#{
ViewData["Title"] = "Create";
}
<hr />
<div>
<form asp-action="Create">
<div class="form-group row">
#foreach (var item in Model.User)
{
#Html.HiddenFor(model => item)
}
<label asp-for="TimeDue" class="col-sm-2 col-form-label control-label"></label>
<div class="col-sm-8">
<input asp-for="TimeDue" value="" class="form-control" />
</div>
</div>
<div class="form-group row">
<label asp-for="PostPrimaryCarbanTankTp1" class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" asp-for="PostPrimaryCarbanTankTp1" />
</label>
</div>
</div>
</div>
<div class="form-group row">
<label asp-for="Comments" class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<input asp-for="Comments" class="form-control" />
</div>
</div>
<div class="form-group row">
<label asp-for="IsCompleted" class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<div class="form-check">
<input class="form-check-input" asp-for="IsCompleted" />
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Technician</label>
<div class="col-sm-8">
<select asp-for="Selected" asp-items=#(new SelectList(Model.User,"Id","Name"))>
<option value="">Select...</option>
</select>
#*<span asp-validation-for="Selected" class="text-danger"></span>*#
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">RN</label>
<div class="col-sm-8">
<select asp-for="RnSelected" asp-items=#(new SelectList(Model.User,"Id","Name"))>
<option value="">Select...</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<input type="submit" value="Create" class="btn btn-secondary" />
</div>
</div>
<div><span asp-validation-for="TimeDue" class="text-danger"></span></div>
<div><span asp-validation-for="Comments" class="text-danger"></span></div>
<div><span asp-validation-for="IsCompleted" class="text-danger"></span></div>
</form>
</div>
I tested your code and found that it runs very well in my project.
Except for TimeDue, the field is not successfully bound, the rest of the fields are bound successfully.
I don’t know if you have the same problem. The TimeDue is not successful binding is because you set the Value in the view.
Please delete the value in this field in the view:
<input asp-for="TimeDue" class="form-control" />
Result:
By the way,your User is null only because your User is not successfully bound, you can modify your loop code as follows:
#for (int i = 0; i < Model.User.Count(); i++)
{
<input type="hidden" name="User[#i].Id" value=#Model.User[i].Id />
<input type="hidden" name="User[#i].Name" value=#Model.User[i].Name />
}
Then in your Create action:
[HttpPost]
public IActionResult Create(ChloramineLogEditSaveViewModel clEditSaveViewModel)
{
return View(clEditSaveViewModel);
}
Result:
Edit:
My codes:
Controller:
public IActionResult Create()
{
var model = new ChloramineLogEditSaveViewModel
{
Id = 1,
Comments = "aaaa",
PostPrimaryCarbanTankTp1 = "fjsdgk",
TimeDue = "bbbbbb",
IsCompleted=true,
RnSelected="gggg",
Selected="sgs",
User=new List<User>
{
new User{
Id=1,
Name="aa"
},
new User
{
Id=2,
Name="bb"
}
}
};
return View(model);
}
[HttpPost]
public IActionResult Create(ChloramineLogEditSaveViewModel clEditSaveViewModel)
{
return View(clEditSaveViewModel);
}
View:
<form asp-action="Create">
<div class="form-group row">
#for (int i = 0; i < Model.User.Count(); i++)
{
<input type="hidden" name="User[#i].Id" value=#Model.User[i].Id />
<input type="hidden" name="User[#i].Name" value=#Model.User[i].Name />
}
<label asp-for="TimeDue" class="col-sm-2 col-form-label control-label"></label>
<div class="col-sm-8">
<input asp-for="TimeDue" class="form-control" />
</div>
</div>
<div class="form-group row">
<label asp-for="PostPrimaryCarbanTankTp1" class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" asp-for="PostPrimaryCarbanTankTp1" />
</label>
</div>
</div>
</div>
<div class="form-group row">
<label asp-for="Comments" class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<input asp-for="Comments" class="form-control" />
</div>
</div>
<div class="form-group row">
<label asp-for="IsCompleted" class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<div class="form-check">
<input class="form-check-input" asp-for="IsCompleted" />
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Technician</label>
<div class="col-sm-8">
<select asp-for="Selected" asp-items=#(new SelectList(Model.User,"Id","Name"))>
<option value="">Select...</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">RN</label>
<div class="col-sm-8">
<select asp-for="RnSelected" asp-items=#(new SelectList(Model.User,"Id","Name"))>
<option value="">Select...</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<input type="submit" value="Create" class="btn btn-secondary" />
</div>
</div>
<div><span asp-validation-for="TimeDue" class="text-danger"></span></div>
<div><span asp-validation-for="Comments" class="text-danger"></span></div>
<div><span asp-validation-for="IsCompleted" class="text-danger"></span></div>
</form>

including the appended variable to the data with other variable in ajax

Hello and good day everyone, I am having a problem in ajax. I have a variable named fd that contains object. But i cant find a way to put it together with other variable in "data:". I just want to pass the data of fd and also the other variables from other inputs of my form. Thank you very much.
$('#register_btn').click(function(e) {
var fd = new FormData();
var files = $('#image')[0].files[0];
fd.append('image',files);
var val1 = $('#email').val();
var val2 = $('#firstname').val();
var val3 = $('#middlename').val();
var val4 = $('#lastname').val();
var val5 = $('#emp_status').val();
var val6 = $('input[name=date_hired]').val();
var val7 = $('#account_type').val();
var val8 = $('#notes').val();
var val9 = $('#position').val();
var val10 = $('#cp_number').val();
var val11 = $('#tel_number').val();
var val12 = $('#address').val();
$.ajax({
type: 'POST',
url: 'process/add_employee_process.php',
contentType: false,
cache: false,
processData:false,
data: {email: val1, firstname: val2, middlename: val3, lastname: val4, emp_status: val5, date_hired: val6, account_type: val7, notes: val8, position: val9, cp_number: val10, tel_number: val11, address: val12,fd},
success:function(html) {
if(html=="Failed"){
$("#gifcheckmark").attr('src','../campfire.gif');
$("#gifcheckmark").css('display','inline');
$("#gifcheckmark").css('width','inline');
$("#notif_message").text("Failed");
$("#register_btn").css('display','none');
$("#decline_btn").css('display','none');
}
else{
$("#notif_message").text("Success");
$("#gifcheckmark").css('display','inline');
$("#gifcheckmark").css('width','inline');
$("#register_btn").css('display','none');
$("#decline_btn").css('display','none');
setInterval(successGif, 1600);
$('#qr').load('../phpqrcode/index.php');
$('#qr').show();
}
}
});
});
This is the form
<form role="form" style="width: 100%;">
<div class="box-body">
<div class="box-header with-border col-xs-12">
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-remove"></i></button>
</div>
</div>
<div class="form-group col-md-3">
<label for="">Email </label>
<input type="email" id="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
</div>
<div class="form-group col-md-3">
<label for="">Firstname </label>
<input type="text" id="firstname" class="form-control" id="" placeholder="Firstname">
</div>
<div class="form-group col-md-3">
<label for="">Middlename </label>
<input type="text" id="middlename" class="form-control" id="" placeholder="Middlename">
</div>
<div class="form-group col-md-3">
<label for="">Lastname </label>
<input type="text" id="lastname" class="form-control" id="" placeholder="Lastname">
</div>
<div class="form-group col-md-3">
<label for="">Employee Status </label>
<input type="text" id="emp_status" class="form-control" id="" placeholder="Employee Status">
</div>
<div class="form-group col-md-3">
<label for="">Date Hired </label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" name="date_hired" class="form-control pull-right" id="datepicker">
</div>
</div>
<div class="form-group col-md-3">
<label for="">Account Type </label>
<input type="text" id="account_type" class="form-control" id="" placeholder="Account Type">
</div>
<div class="form-group col-md-3">
<label for="">Notes </label>
<input type="text" id="notes" class="form-control" id="" placeholder="Notes">
</div>
<div class="form-group col-md-3">
<label for="">Positions </label>
<input type="text" id="position" class="form-control" id="" placeholder="Positions">
</div>
<div class="form-group col-md-3">
<label for="">Cellphone Number </label>
<input type="text" id="cp_number" class="form-control" id="" placeholder="Cellphone Number">
</div>
<div class="form-group col-md-3">
<label for="">Telephone Number </label>
<input type="text" id="tel_number" class="form-control" id="" placeholder="Telephone Number">
</div>
<div class="form-group col-md-3">
<label for="">Address </label>
<input type="text" id="address" class="form-control" id="" placeholder="Address">
</div>
<div class="form-group col-xs-12">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" id="image" name="image">
</div>
</div>
<!-- /.box-body -->
<div class="col-xs-2">
<center><button type="button" id="confirm_btn" class="btn btn-primary" data-toggle="modal" data-target="#modal-default">
Submit
</button></center>
</div>
</form>
This is the add_employee_process.php
$db = mysqli_connect('localhost', 'root','','cjwebsolutions');
$image = $_FILES['image']['name'];
$target = "image/".basename($image);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
$emp_id = make_emp_id($_POST['date_hired']);
$_POST['emp_id'] = $emp_id;
// Required field names
$required_fields = array('email','firstname','middlename','lastname', 'emp_status', 'date_hired','account_type','notes','position','cp_number','tel_number','address','emp_id');
$data_insert_fields = array('email','firstname','middlename','lastname', 'emp_status', 'date_hired','account_type','notes','position','cp_number','tel_number','address','emp_id');
if (check_empty_fields($required_fields)) {
echo "Failed";
}
else
{
data_insert($data_insert_fields,"cj_accounts");
}

Resources