I am try to understand what happened with checkbox status. So I have Create Page where I insert Patient
and when I click Emergency to True in Index Page I always get False
IndexPage.cshtml
#if (Model.Count() > 0)
{
<table class="table table-bordered table-striped" style="width:100%">
<thead>
<tr>
<th>
Doctor Full Name - CODE
</th>
<th>
Patient Full Name
</th>
<th>
Date and Time
</th>
<th>
Emergency
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var obj in Model)
{
<tr>
<td width="25%">#obj.Doctor.Firstname #obj.Doctor.Lastname #obj.Doctor.Code</td>
<td width="25%">#obj.Patient.FirstName #obj.Patient.LastName</td>
<td width="25%">#obj.DateAndTime</td>
<td width="25%" class="blink_me">#obj.Emergency</td>
<td class="text-center">
<div class="w-75 btn-group" role="group">
<a asp-route-Id="#obj.Id" asp-action="Upsert" class="btn btn-primary mx-2">
<i class="fas fa-edit"></i>
</a>
<a asp-route-Id="#obj.Id" asp-action="Delete" class="btn btn-danger mx-2">
<i class="far fa-trash-alt"></i>
</a>
</div>
</td>
</tr>
}
</tbody>
</table>
}
else
{
<p> No Admission Patient exists.</p>
}
Create
#model BergClinics.Models.ViewModel.AdmisionVM
#{
ViewData["Title"] = "Upsert";
var title = "Create Admission Patient";
}
<form method="post" enctype="multipart/form-data">
#if (Model.AdmissionPatient.Id != 0)
{
<input asp-for="AdmissionPatient.Id" hidden />
title = "Edit Admission Patient";
}
<div class="border p-3">
<div class="form-group row">
<h2 class="text-info pl-3">#title</h2>
</div>
<div class="row">
<div class="col-8">
<div class="form-group row py-2">
<div class="col-4">
<label>Doctor Full Name : </label>
</div>
<div class="col-8">
<select asp-for="AdmissionPatient.DoctorId" asp-items="#Model.DoctorSelectList" class="form-control">
<option disabled selected>--Select Docotor--</option>
</select>
</div>
</div>
<div class="form-group row py-2">
<div class="col-4">
<label>Patient Full Name: </label>
</div>
<div class="col-8">
<select asp-for="AdmissionPatient.PatientId" asp-items="#Model.PatientSelectList" class="form-control">
<option disabled selected>--Select Patient--</option>
</select>
</div>
</div>
<div class="form-group row py-2">
<div class="col-4">
<label>Date and Time :</label>
</div>
<div class="col-8">
<input asp-for="AdmissionPatient.DateAndTime" asp-format="{0:dd/MM/yyyy}" type="text" name="date" class="form-control datepicker" autocomplete="off">
</div>
</div>
<div class="form-group row py-2">
<div class="col-4">
<label>Patient Image :</label>
</div>
<div class="col-3">
<input type="file" name="files" id="imageBox" multiple class="form-control" />
</div>
</div>
<div class="form-group row py-2">
<div class="col-4">
<label>Emergency reception :</label>
</div>
<div class="col-8">
<input type="checkbox" class="form-control" id="emergencyId">
<label class="form-check-label" for="exampleCheck1"></label>
</div>
</div>
<div class="form-group row py-2">
<div class="col-8 offset-4 row">
<div class="col">
#if (Model.AdmissionPatient.Id != 0)
{
//update
<input type="submit" class="btn btn-info w-100" value="Update" />
}
else
{
//create
<input type="submit" onclick="return validateInput()" class="btn btn-primary w-100" value="Create" />
}
</div>
</div>
</div>
</div>
<div class="col-4">
#if (Model.AdmissionPatient.Id != 0)
{
<img src="#Constans.imagePath#Model.AdmissionPatient.Image" width="100%" style="border-radius:5px; border:1px solid #bbb" />
}
</div>
</div>
</div>
</form>
#section Scripts{
#{
<partial name="_ValidationScriptsPartial" />
}
<script>
function validateInput() {
if (document.getElementById("imageBox").value == "") {
Swal.fire(
'Error!',
'Please upload an Image!',
'error'
)
return false;
}
return true;
}
</script>
<script>
$('.datepicker').datepicker({
startDate: new Date()
});
</script>
}
Controller Post Action
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Upsert(AdmisionVM admissionVM)
{
if (ModelState.IsValid)
{
var files = HttpContext.Request.Form.Files;
string webRootPath = _webHostEnvironment.WebRootPath;
if (admissionVM.AdmissionPatient.Id == 0)
{
//Creating
string upload = webRootPath + Constans.imagePath;
string fileName = Guid.NewGuid().ToString();
string extension = Path.GetExtension(files[0].FileName);
using (var fileStream = new FileStream(Path.Combine(upload, fileName + extension), FileMode.Create))
{
files[0].CopyTo(fileStream);
}
admissionVM.AdmissionPatient.Image = fileName + extension;
_db.AdmissionPacients.Add(admissionVM.AdmissionPatient);
}
else
{
//Updating
var objFromDb = _db.AdmissionPacients.AsNoTracking().FirstOrDefault(u => u.Id == admissionVM.AdmissionPatient.Id);
if (files.Count > 0)
{
string upload = webRootPath + Constans.imagePath;
string fileName = Guid.NewGuid().ToString();
string extension = Path.GetExtension(files[0].FileName);
var oldFile = Path.Combine(upload, objFromDb.Image);
if (System.IO.File.Exists(oldFile))
{
System.IO.File.Delete(oldFile);
}
using (var fileStream = new FileStream(Path.Combine(upload, fileName + extension), FileMode.Create))
{
files[0].CopyTo(fileStream);
}
admissionVM.AdmissionPatient.Image = fileName + extension;
}
else
{
admissionVM.AdmissionPatient.Image = objFromDb.Image;
}
_db.AdmissionPacients.Update(admissionVM.AdmissionPatient);
}
_db.SaveChanges();
return RedirectToAction("Index");
}
admissionVM.PatientSelectList = _db.Patients.Select(i => new SelectListItem
{
Text = i.FirstName + i.LastName,
Value = i.Id.ToString()
});
admissionVM.DoctorSelectList = _db.Doctors.Select(i => new SelectListItem
{
Text = i.Firstname + i.Lastname,
Value = i.Id.ToString()
});
return View(admissionVM);
}
try add name to this line:
<input type="checkbox" class="form-control" id="emergencyId">
to
<input name="Emergency" type="checkbox" class="form-control" id="emergencyId">
Related
I hope some can help me with this.
I have a list within a model and I want to add objects to that list using a form in a razor view before I save it to a database
This is the model that I have:
public class ActivityForm
{
public string Name { get; set; }
public string Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int Points { get; set; }
public List<Award> Awards { get; set; }
}
This is the code for my view:
#model ActivityForm
#{
ViewData["Title"] = "Activity Details";
}
<section class="my-sm-5">
<div class="container">
<div class="section-header d-flex mb-5">
<h1 class="h-02 flex-grow-1">Activity Details</h1>
</div>
<div class="row">
<div class="col-md-7">
<div class="section-header d-flex mb-5">
<h1 class="h-04 flex-grow-1">Form</h1>
</div>
<form id="form" class="row g-3 w-90" asp-action="Create">
<div class="col-md-12">
<label asp-for="Name" class="form-label">#Html.DisplayNameFor(model => model.Name)</label>
<input asp-for="Name" type="text" class="form-control" id="inputEmail4"
placeholder="#Html.DisplayNameFor(model => model.Name)">
<span asp-validation-for="Name" class="invalid-feedback"></span>
</div>
<div class="col-12">
<label asp-for="Description" class="form-label">#Html.DisplayNameFor(model =>
model.Description)</label>
<textarea asp-for="Description" class="form-control" id="exampleFormControlTextarea1" rows="5"
placeholder="#Html.DisplayNameFor(model => model.Description)"></textarea>
<span asp-validation-for="Description" class="invalid-feedback"></span>
</div>
<div class="col-md-4">
<label asp-for="StartDate" class="form-label">#Html.DisplayNameFor(model =>
model.StartDate)</label>
<input asp-for="StartDate" type="date" class="form-control"
placeholder="#Html.DisplayNameFor(model => model.StartDate)">
<span asp-validation-for="StartDate" class="invalid-feedback"></span>
</div>
<div class="col-md-4">
<label asp-for="EndDate" class="form-label">#Html.DisplayNameFor(model => model.EndDate)</label>
<input asp-for="EndDate" type="date" class="form-control"
placeholder="#Html.DisplayNameFor(model => model.EndDate)">
<span asp-validation-for="EndDate" class="invalid-feedback"></span>
</div>
<div class="col-md-4 mb-6">
<label asp-for="Points" class="form-label">#Html.DisplayNameFor(model => model.Points)</label>
<input asp-for="Points" type="number" class="form-control"
placeholder="#Html.DisplayNameFor(model => model.Points)">
<span asp-validation-for="Points" class="invalid-feedback"></span>
</div>
<div class="col-8 d-grid gap-2">
<a class="btn btn-primary mb-2" data-bs-toggle="modal" data-bs-target="#add-award">Add award</a>
<div class="row">
<div class="col-md-6">
<a class="btn btn-outline-primary w-100" data-bs-toggle="modal"
data-bs-target="#cancel-activity">Cancel</a>
</div>
<div class="col-md-6">
<a class="btn btn-outline-primary w-100" data-bs-toggle="modal"
data-bs-target="#post-activity">Post Activity</a>
</div>
</div>
</div>
</form>
</div>
<div class="col-md-5">
<div class="section-header d-flex mb-5">
<h1 class="h-04 flex-grow-1">Awards</h1>
</div>
<table class="table">
<thead>
<tr>
<th scope="col">Award name</th>
<th scope="col">Description</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < 1; i++)
{
<tr>
<td>Award Name</td>
<td>Award Description</td>
<td>
<a class="btn btn-outline-primary btn-sm">Edit</a>
<a class="btn btn-outline-primary btn-sm">Remove</a>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
</section>
<div class="modal" id="add-award" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content br-20 pd-20">
<div class="modal-header justify-content-center">
<h5 class="modal-title h-04 text-prim-color">Award details</h5>
</div>
<form class="row g-3">
<div class="modal-body">
<div class="row g-3">
<div class="col-md-12">
<label asp-for="Award.Name" class="form-label">Name</label>
<input asp-for="Award.Name" type="text" class="form-control" id="inputEmail4">
</div>
<div class="col-12">
<label asp-for="Award.Description" for="inputAddress" class="form-label">Description</label>
<textarea asp-for="Award.Description" class="form-control" id="exampleFormControlTextarea1" rows="5"></textarea>
</div>
</div>
</div>
<div class="modal-footer justify-content-center">
<button type="button" class="btn btn-outline-primary w-100" data-bs-dismiss="modal">Close</button>
<input class="btn btn-primary w-100" type="submit" value="Confirm"></input>
</div>
</form>
</div>
</div>
</div>
My form is within a modal and when I click the submit button I want to create an Award object with the values from the form. After the object is created I want to add it to the Awards List and have the changes reflect on the view.
This is what the View looks like:
View with modal
And this is how it will look like after the object has been added:
View after object is added
You should first fix some issues:
Right now your form does not have a binding for the ActivityForm.Awards property. You should change:
<tbody>
#for (int i = 0; i < 1; i++)
{
<tr>
<td>Award Name</td>
<td>Award Description</td>
<td>
<a class="btn btn-outline-primary btn-sm">Edit</a>
<a class="btn btn-outline-primary btn-sm">Remove</a>
</td>
</tr>
}
</tbody>
To:
<tbody>
#for (var i = 0; i < Model.Awards.Count; i++)
{
<input type="hidden" asp-for="#Model.Awards[i].Name" />
<input type="hidden" asp-for="#Model.Awards[i].Description" />
<tr>
<td>#Model.Awards[i].Name</td>
<td>#Model.Awards[i].Description</td>
<td>
<a class="btn btn-outline-primary btn-sm">Edit</a>
<a class="btn btn-outline-primary btn-sm">Remove</a>
</td>
</tr>
}
</tbody>
Documentation for binding model to a collection: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0#collections-1
Your form should wrap around both Form and Awards sections:
<form id="form" class="row g-3 w-90" asp-action="Create">
<div class="col-md-7">
<div class="section-header d-flex mb-5">
<h1 class="h-04 flex-grow-1">Form</h1>
</div>
...
</div>
<div class="col-md-5">
<div class="section-header d-flex mb-5">
<h1 class="h-04 flex-grow-1">Awards</h1>
</div>
...
</div>
</form>
You should also change:
<a class="btn btn-outline-primary w-100" data-bs-toggle="modal" data-bs-target="#post-activity">Post Activity</a>
to an actual submit button:
<button type="submit" class="btn btn-outline-primary w-100">Post Activity</button>
Now if you manually add some awards to the Awards list from your Controller,
return View(new ActivityForm
{
Awards = new List<Award>
{
new Award { Name = "Name", Description = "Descr" },
new Award { Name = "Award 2", Description = "Descr 2" }
}
});
the awards will be displayed properly and also when you submit the form the ActivityForm.Awards list will be populated with the awards you added manually.
These issues need to be fixed before you go on and implement the add award form inside the modal.
I'm having trouble with a list within my model returning as null even tho in the view it clearly has some value.
I had trouble trying to add objects to my model's list, someone helped me and my problem was half solved. This is the code I came up with after the help
My view:
#model ActivityForm
#{
ViewData["Title"] = "Activity Details";
}
<section class="my-sm-5">
<div class="container">
<div class="section-header d-flex mb-5">
<h1 class="h-02 flex-grow-1">Activity Details</h1>
</div>
<div class="row">
<div class="col-md-7">
<div class="section-header d-flex mb-5">
<h1 class="h-04 flex-grow-1">Form</h1>
</div>
<form id="form" class="row g-3 w-90" asp-action="Create">
<div class="col-md-12">
<label asp-for="Name" class="form-label">#Html.DisplayNameFor(model => model.Name)</label>
<input asp-for="Name" type="text" class="form-control" id="inputEmail4"
placeholder="#Html.DisplayNameFor(model => model.Name)">
<span asp-validation-for="Name" class="invalid-feedback"></span>
</div>
<div class="col-12">
<label asp-for="Description" class="form-label">#Html.DisplayNameFor(model =>
model.Description)</label>
<textarea asp-for="Description" class="form-control" id="exampleFormControlTextarea1" rows="5"
placeholder="#Html.DisplayNameFor(model => model.Description)"></textarea>
<span asp-validation-for="Description" class="invalid-feedback"></span>
</div>
<div class="col-md-4">
<label asp-for="StartDate" class="form-label">#Html.DisplayNameFor(model =>
model.StartDate)</label>
<input asp-for="StartDate" type="date" class="form-control"
placeholder="#Html.DisplayNameFor(model => model.StartDate)">
<span asp-validation-for="StartDate" class="invalid-feedback"></span>
</div>
<div class="col-md-4">
<label asp-for="EndDate" class="form-label">#Html.DisplayNameFor(model => model.EndDate)</label>
<input asp-for="EndDate" type="date" class="form-control"
placeholder="#Html.DisplayNameFor(model => model.EndDate)">
<span asp-validation-for="EndDate" class="invalid-feedback"></span>
</div>
<div class="col-md-4 mb-6">
<label asp-for="Points" class="form-label">#Html.DisplayNameFor(model => model.Points)</label>
<input asp-for="Points" type="number" class="form-control"
placeholder="#Html.DisplayNameFor(model => model.Points)">
<span asp-validation-for="Points" class="invalid-feedback"></span>
</div>
<div class="col-8 d-grid gap-2">
<a class="btn btn-primary mb-2" data-bs-toggle="modal" data-bs-target="#add-award">Add award</a>
<div class="row">
<div class="col-md-6">
<a class="btn btn-outline-primary w-100" data-bs-toggle="modal"
data-bs-target="#cancel-activity">Cancel</a>
</div>
<div class="col-md-6">
<a class="btn btn-outline-primary w-100" data-bs-toggle="modal"
data-bs-target="#post-activity">Post Activity</a>
</div>
</div>
</div>
<div class="modal" id="add-award" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content br-20 pd-20">
<div class="modal-header justify-content-center">
<h5 class="modal-title h-04 text-prim-color">Award details</h5>
</div>
<div class="row g-3">
<div class="modal-body">
<div class="row g-3">
<div class="col-md-12">
<label asp-for="Award.Name" class="form-label">Name</label>
<input asp-for="Award.Name" type="text" class="form-control"
id="award-name">
</div>
<div class="col-12">
<label asp-for="Award.Description" for="inputAddress"
class="form-label">Description</label>
<textarea asp-for="Award.Description" class="form-control"
id="award-description" rows="5"></textarea>
</div>
</div>
</div>
<div class="modal-footer justify-content-center">
<button type="button" class="btn btn-outline-primary w-100"
data-bs-dismiss="modal">Close</button>
<input class="btn btn-primary w-100" type="submit" value="Confirm"></input>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="col-md-5">
<div class="section-header d-flex mb-5">
<h1 class="h-04 flex-grow-1">Awards</h1>
</div>
<table class="table">
<thead>
<tr>
<th scope="col">Award name</th>
<th scope="col">Description</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
#if (Model.Awards != null)
{
foreach (var item in Model.Awards)
{
<tr>
<td>#item.Name</td>
<td>#item.Description</td>
<td>
<a class="btn btn-outline-primary btn-sm">Edit</a>
<a class="btn btn-outline-primary btn-sm">Remove</a>
</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
</div>
</section>
Method in controller:
[HttpPost]
public async Task<IActionResult> Create(ActivityForm data)
{
var award = data.Award;
if (award.Name != null && award.Description != null)
{
if (data.Awards == null) data.Awards = new List<AwardForm>();
data.Awards.Add(new AwardForm { Name = award.Name, Description = award.Description });
data.Award.Name = "";
data.Award.Description = "";
return View(data);
}
if (!ModelState.IsValid)
{
return View(data);
}
string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
await service.NewActivityAsync(data, userId);
return RedirectToAction(nameof(Index));
}
Model
public class ActivityForm
{
public string Name { get; set; }
public string Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int Points { get; set; }
public AwardForm Award { get; set; }
public List<AwardForm> Awards { get; set; }
}
Everything was now working as intended but I had one more issue left. When I try to add another Award to the list, the list is returned to the controller method as null.
I'm not really sure if the issue is related to binding, I have noticed that every other value is bound and is returning the expected value except the list which is not bound.
Change the foreach loop to:
<tbody>
#if (Model.Awards != null)
{
#for (var i = 0; i < Model.Awards.Count; i++)
{
<input type="hidden" asp-for="#Model.Awards[i].Name" />
<input type="hidden" asp-for="#Model.Awards[i].Description" />
<tr>
<td>#Model.Awards[i].Name</td>
<td>#Model.Awards[i].Description</td>
<td>
<a class="btn btn-outline-primary btn-sm">Edit</a>
<a class="btn btn-outline-primary btn-sm">Remove</a>
</td>
</tr>
}
}
</tbody>
This has same effect to what #Victor suggested but using input tag helper instead of html helper.
Documentation for binding model to a collection: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0#collections-1
Also your form should wrap around both Form and Awards sections:
<form id="form" class="row g-3 w-90" asp-action="Create">
<div class="col-md-7">
<div class="section-header d-flex mb-5">
<h1 class="h-04 flex-grow-1">Form</h1>
</div>
...
</div>
<div class="col-md-5">
<div class="section-header d-flex mb-5">
<h1 class="h-04 flex-grow-1">Awards</h1>
</div>
...
</div>
</form>
The list binding context should include indexes to work properly.
Add to following code located below right after declaration of the <form> tag:
<form id="form" class="row g-3 w-90" asp-action="Create">
#if (Model.Awards != null)
{
for (int i=0; i < Model.Awards.Count; i++)
{
#Html.Hidden("Awards[" + i + "].Name", Model.Awards[i].Name)
#Html.Hidden("Awards[" + i + "].Description", Model.Awards[i].Description)
}
}
... your markup and control that performs the submit are located here
</form>
To be a part of the binding context these hidden fields should be declared inside the <form> from that the submit is performing.
I started to learn some basic c# and im trying to find my way into ASP.net
I am running the following code with some help from this video: https://www.youtube.com/watch?v=C5cnZ-gZy2I (time stamp: 1 hour and 50min)
public class BestellenModel : PageModel
{
private ApplicationDbContext _db;
public BestellenModel(ApplicationDbContext db)
{
_db = db;
}
[BindProperty]
public Bedrijven Bedrijven { get; set; }
public async Task OnGet(int id)
{
Bedrijven = await _db.Bedrijven.FindAsync(id);
}
}
}
In the video whenever the edit button is pressed the right data from the data base appears on screen. For me nothing appears but whenever i click on my url and hit enter again the data appears.
I tried the debug option within VS and i saw that the line FindAsync doesn't run when hitting the button. But when i click enter on the url then it runs the code. My url looks like this: https://localhost:7005/Bedrijfslijst/Bestellen?id=32
Can anyone tell me what i am missing here? because i am a bit stuck.
Edit:
Now whenever the client Clicks on the "kopen" button it needs to render the data from the db to the fields.
This is a screenshot from the yt video, its supposed to show the data when the page is loaded. For me its not loading but whenever i click on the url and hit enter then the db data will load in.
cshtml script:
#page
#model test1v1.Pages.Bedrijfslijst.BestellenModel
<br />
<h2 class="text-primary">Rapport bestellen</h2>
<br />
<div class="border container" style="padding:120px;">
<form method="post">
<div class="text-danger" asp-validation-summary="ModelOnly"></div>
<div class="form-group row" style="padding:10px;">
<div class="col-4">
<label asp-for="Bedrijven.Kvk"></label>
</div>
<div class="col-4">
<input asp-for="Bedrijven.Kvk" class="form-control" />
</div>
<span asp-validation-for="Bedrijven.Kvk" class="text-danger"></span>
</div>
<div class="form-group row" style="padding:10px;">
<div class="col-4">
<label asp-for="Bedrijven.Bedrijfsnaam"></label>
</div>
<div class="col-4">
<input asp-for="Bedrijven.Bedrijfsnaam" class="form-control" />
</div>
<span asp-validation-for="Bedrijven.Bedrijfsnaam" class="text-danger"></span>
</div>
<div class="form-group row" style="padding:10px;">
<div class="col-4">
<label asp-for="Bedrijven.Adres"></label>
</div>
<div class="col-4">
<input asp-for="Bedrijven.Adres" class="form-control" />
</div>
<span asp-validation-for="Bedrijven.Adres" class="text-danger"></span>
</div>
<div class="form-group row" style="padding:10px;">
<div class="col-3 offset-4">
<input type ="submit" value="Bestellen" class="btn btn-success form-control" />
</div>
<div class="col-3">
<a asp-page="index" class="btn btn-primary form-control">Terug</a>
</div>
</div>
</form>
</div>
#section Scripts{
<partial name ="_ValidationScriptsPartial"/>
}
Edit2:
#page
#model test1v1.Pages.Bedrijfslijst.IndexModel
<br />
<div class="container row p-0 m-0">
<div class="col-9">
<h2 class="text-primary">Bedrijf Lijst</h2>
</div>
<div class="col-3">
<a asp-page="Zoeken" class="btn btn-primary form-control text-white">Bedrijf Zoeken</a>
</div>
<div class= "col-10 border p-4 mt-4">
<form method="post">
#if (Model.Bedrijven.Count() > 0)
{
<table class="table table-striped border">
<tr class="table-secondary">
<th>
<label asp-for="Bedrijven.FirstOrDefault().Kvk"></label>
</th>
<th>
#*#Html.DisplayNameFor(m=>m.Books.FirstOrDefault().Author)*#
<label asp-for="Bedrijven.FirstOrDefault().Bedrijfsnaam"></label>
</th>
<th>
<label asp-for="Bedrijven.FirstOrDefault().Adres"></label>
</th>
<th>
</th>
</tr>
#foreach (var item in Model.Bedrijven)
{
<tr>
<td>
#Html.DisplayFor(m=>item.Bedrijfsnaam)
</td>
<td>
#Html.DisplayFor(m=>item.Kvk)
</td>
<td>
#Html.DisplayFor(m=>item.Adres)
</td>
<td>
<button asp-page="Bestellen" asp-route-id="#item.Id" class="btn btn-primary btn-sm">Kopen</button>
</td>
</tr>
}
</table>
}
else
{
<p>Geen Bedrijven Gevonden.</p>
}
</form>
</div>
</div>
Hello i want to fill text when click edit button but value not fill in textbox ,
when i debug this code json function return value and also value show in javascript code but when pop model show then value not show in textbox . any one tell where i am wrong and what is the problem in this code.
Json Function
#region Select Requisition Main Select
public JsonResult mRequisitionmain_Select(Int64 Req_ID)
{
try
{
Requisition mReq = new Requisition();
con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select Req_ID,ReqNo,Comp_ID, GL_Year,ReqDate,Job,ApprovedBy,UserName, IsApproved from RequisitionMain where Req_ID='" + Req_ID + "'", con);
cmd.CommandType = CommandType.Text;
con.Open();
DataTable mDT = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(mDT);
mReq.Req_ID = mDT.Rows[0]["Req_ID"].ToString();
mReq.ReqNo = mDT.Rows[0]["ReqNo"].ToString();
mReq.Comp_ID = 1;
mReq.GL_Year = "2018-2019";
mReq.ReqDate = mDT.Rows[0]["ReqDate"].ToString();
mReq.Job = mDT.Rows[0]["Job"].ToString();
mReq.Approvedby = mDT.Rows[0]["ApprovedBy"].ToString();
mReq.Username = Session["AgentName"].ToString();
mReq.IsApproved = Convert.ToBoolean(mDT.Rows[0]["IsApproved"]);
con.Close();
return Json(mReq, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
javascript
function getbyID(Req_ID) {
$.ajax({
url: "/Home/mRequisitionmain_Select?Req_ID=" + Req_ID,
type: "GET",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (result) {
$('#Req_ID').val(result.Req_ID);
$('#ReqNo').val(result.ReqNo);
$('#ReqDate').val(result.ReqDate);
$('#Job').val(result.Job);
$('#Approvedby').val(result.Approvedby);
$('#IsApproved').val(result.IsApproved);
$('#updateModel').modal('show');
$('#UpdateReq').show();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
return false;
}
HTML
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr id="lblhead">
<th>Requisition Date</th>
<th>Job</th>
<th>Approved By</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.items)
{
<tr>
<td style="text-align:left; width:150px;">#Html.DisplayFor(modelItem => item.ReqDate)</td>
<td>#Html.DisplayFor(modelItem => item.Job)</td>
<td style="text-align:left; width:150px;">#Html.DisplayFor(modelItem => item.Approvedby)</td>
<td style="text-align:center; width:40px;">
<a style='color:blue; text-decoration: underline; font-weight: bold;' href='#Url.Action("RequisitionDetail", "Home",new { item.Req_ID })'> View</a> |
<a data-toggle="modal" data-target="#updateModel" onclick="getbyID(#item.Req_ID)">
<i class="fa fa-edit"></i>
</a>
</td>
</tr>
}
</tbody>
<tfoot>
</tfoot>
</table>
<div class="modal fade" id="updateModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg modal-notify modal-info" role="document">
<!--Content-->
<div class="modal-content" style="width:140%">
<!--Header-->
<div class="modal-header">
<p class="heading lead">Update Requisition</p>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" class="white-text">×</span>
</button>
</div>
<!--Body-->
<form id="NewOrderForm">
<div class="modal-body">
<div class="form-row">
<div class="col" id="Req_ID">
<!-- Requisition Req_ID -->
<div class="md-form">
#Html.TextBoxFor(m=>m.Req_ID, new { #class = "form-control mr-sm-3", #id = "ReqID", Required = true })
</div>
</div>
<div class="col">
<!-- Requisition Req_NO -->
<div class="md-form">
#Html.TextBoxFor(m=>m.ReqNo, new { #class = "form-control mr-sm-3", #id = "ReqNo", Required = true })
<label for="lblRequisition">Requisition No.</label>
</div>
</div>
<div class="col">
<!-- Requisition Date -->
<div class="md-form">
#Html.TextBoxFor(m => m.ReqDate, new { #class = "form-control", #id = "ReqDate", Required = true })
<label for="lblRequisitionDatepicker">Requisition Date</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
#Html.TextBoxFor(m => m.Job, new { #class = "form-control", #id = "Job", Required = true })
<label for="lbljob">Job</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
#Html.TextBoxFor(m => m.Approvedby, new { #class = "form-control", #id = "Approvedby", Required = true })
<label for="lblApprovedby">Approved by</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
<div class="custom-control custom-checkbox">
<span style="float:right">
#Html.CheckBoxFor(m => m.IsApproved, new { #class = "custom-control-input", #id = "IsApproved" })
<label class="custom-control-label" for="defaultChecked2">Approved</label>
</span>
</div>
</div>
</div>
</div>
<!--Detail-->
<h5 style="margin-top:10px;color:#ff6347">Requisition Details</h5>
<hr />
<div>
<div class="form-row">
<div class="col-md-4">
<!-- Requisition Date -->
<div class="md-form">
#Html.DropDownListFor(m => m.ItemCode, ViewBag.Items as List<SelectListItem>, new { #class = "form-control", id = "ItemCode", Required = true })
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
<input type="number" id="Qty" name="Qty" placeholder="Qty" class="form-control" ,Required=true />
<label for="lbljob">Qty</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
<input type="text" id="Remarks" name="Remarks" placeholder="Remarks" class="form-control" ,Required=true />
<label for="lblRemarks">Remarks</label>
</div>
</div>
<div class="col-md-2 col-lg-offset-4">
<a id="addToList" class="btn btn-primary">Add To List</a>
</div>
</div>
<table id="detailsTable" class="table">
<thead style="background-color:#007bff; color:white">
<tr>
<th style="width:2%">SrNo.</th>
<th style="width:40%">Items</th>
<th style="width:15%">Qty</th>
<th style="width:30%">Remarks</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-primary" data-dismiss="modal">Close</button>
<button id="UpdateReq" type="submit" class="btn btn-primary">Save Record</button>
</div>
</div>
</form>
view :
<div id="ReportChange">
#{
ViewDataDictionary vDataDictonary = new ViewDataDictionary();
vDataDictonary.Add(new KeyValuePair<string, object>("ReportType", ViewData["ReportType"]));
vDataDictonary.Add(new KeyValuePair<string,object>("Agencias", ViewData["Agencias"]));
vDataDictonary.Add(new KeyValuePair<string, object>("SendType", ViewData["SendType"]));
vDataDictonary.Add(new KeyValuePair<string, object>("OrderStatus", ViewData["OrderStatus"]));
vDataDictonary.Add(new KeyValuePair<string, object>("User", ViewData["User"]));
vDataDictonary.Add(new KeyValuePair<string, object>("ServicesType", ViewData["ServicesType"]));
if (Model.report == null){
Html.RenderPartial("getReport", new ReportSchedule() { StartDate = DateTime.Now, EndDate=DateTime.Now}, vDataDictonary);
}
else {
Html.RenderPartial("getReport", Model.report, vDataDictonary);
}
}
#if (Model.lReport.Count() == 0)
{
<h4 class="alert alert-danger text-center">Error.</h4>
}
else
{
<div class="container-fluid container-fixed-lg bg-white" id="viewform">
<div class="panel panel-transparent">
<div class="panel-heading">
<div class="panel-title"></div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<table class="table table-hover demo-table-search" id="tableWithSearch">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.lReport)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.ReportType.Description)</td>
<td>#(item.EndDate.HasValue ? String.Concat(item.StartDate.ToString("dd/MM/yyyy"), " - ", item.EndDate.Value.ToString("dd/MM/yyyy")) : item.StartDate.ToString("dd/MM/yyyy"))</td>
<td>#item.StartDate - #item.EndTime </td>
<td>#Html.DisplayFor(modelItem=> item.Agency.CorporateName) </td>
<td>#Html.DisplayFor(modelItem=> item.CostCenter.Description)</td>
<td>#Html.DisplayFor(modelItem=> item.User.Name )</td>
<td>#Html.DisplayFor(modelItem=>item.OrderStatus.Description ) </td>
<td>#Html.DisplayFor(modelItem=> item.ServiceType.Description ) </td>
<td>#Html.CheckBox("A", #item.Live.Equals(0) ? false : true, new {disabled="readonly" })</td>
<td class="v-align-middle">
<div class="btn-group">
<input type="button" class="btn btn-info btn-sm" id="#item.ReportScheduleID" onclick="getReport(this.id)" />
#Html.ActionLink(item.Live ? "D" : "A", "Live", new { id = item.CostCenterID }, new { #class ="btn btn-danger btn-sm buttonLive" })
</div>
</td>
</tr>
}
</tbody>
</table>
<div class="row"> </div>
</div>
</div>
</div>
}
My partial view :
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<form id="frm" class="form-horizontal well">
#if (Model.AgencyID.Equals(0))
{
using (Html.BeginForm("getReport", "ReportSchedules"))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(_ => _.ReportScheduleID)
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label col-md-1">Relatório</label>
#Html.DropDownListFor(m=>m.ReportTypeID,(SelectList) ViewData["ReportType"],"Atendimento por Agência")
#Html.ValidationMessageFor(m=>m.ReportTypeID)
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label col-md-1">Início</label>
<input type="text" id="date" name="date" class="col-md-2 smallDate" value="#Model.StartDate.ToShortDateString()"/>
#Html.ValidationMessageFor(m=>m.StartDate)
#Html.TextBoxFor(m=>m.StartTime,new {#class="col-md-1 smallDateMargin"})
#Html.ValidationMessageFor(m => m.StartTime)
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label col-md-1">Periodicidade</label>
#Html.DropDownListFor(m=>m.SendTypeID,(SelectList) ViewData["SendType"],"Selecione")
#Html.ValidationMessageFor(m=>m.SendTypeID)
</div>
</div>
<div class="col-md-10">
<h6>Configurações avançadas<a data-toggle="tooltip" class="tooltipLink" data-original-title="Data até quando o relatório será enviado.">
<span class="glyphicon glyphicon-question-sign"></span>
</a></h6>
<div class="form-group" style="border: 1px dashed #ccc;">
<div class="form-group">
<label class="control-label col-md-1">
<input type="checkbox" name="dateEndSelected" id="dateEndSelected" value="#Model.Live"/> Fim</label>
<input type="text" id="dataFinalSelected" name="dataFinalSelected" style="display:none;" value="false"/>
<input type="text" id="dateFinal" name="dateFinal" style="display:none;"class="col-md-2 smallDate" value="#Model.EndDate.Value.ToShortDateString()"/>
#Html.TextBoxFor(m=>m.EndTime,new {#class="col-md-1 smallDateMargin"})
#Html.ValidationMessageFor(m=>m.EndTime)
</div>
</div>
</div>
<div class="col-md-10">
<h6>Filtrar por:</h6>
<div class="form-group" style="border: 1px dashed #ccc;">
<div class="col-md-10">
#Html.DropDownListFor(m=>m.AgencyID, (SelectList) ViewData["Agencias"],"Agências",new {#class="col-md-1",id="agencia",name="agencia"})
#Html.ValidationMessageFor(m => m.AgencyID)
#Html.DropDownListFor(m=>m.OrderStatusID, (SelectList) ViewData["OrderStatus"],"Status",new {#class="col-md-2"})
#Html.ValidationMessageFor(m=>m.OrderStatusID)
#Html.DropDownListFor(m=>m.UserID, (SelectList) ViewData["User"],"Usuários",new {#class="col-md-3"})
#Html.ValidationMessageFor(m=>m.UserID)
</div>
<div class="col-md-10">
#Html.DropDownList("dpdCostCenter", new List<SelectListItem>(), "Selecione", new { #class = "col-md-1" })
#Html.DropDownListFor(m=>m.ServiceTypeID,(SelectList) ViewData["ServicesType"],"Tipos de atendimento",new {#class="col-md-2"})
#Html.ValidationMessageFor(m=>m.ServiceTypeID)
</div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<div class="input-group pull-right marginTopBot-sm input-group-sm" style="padding-left: 5px;">
<input type="submit" value="Agendar o envio" class="btn btn-success" onclick="$('#getResponse').submit()" />
</div>
</div>
</div>
</div>
}
}
else
But if i click in button submit it goes to the index action of view
public ActionResult Index()
And not to :
[HTTPPOST]
public ActionResult getReport(ReportSchedule model)
{
if (ModelState.IsValid)
{
db.ReportSchedule.Add(model);
db.SaveChanges();
}
else
{
return PartialView(model);
}
return RedirectToAction("Index");
}
But i need submit button call getReport to validate a model and save in db
You have nested forms which are invalid html and not supported. Remove the outer form tag from the partial (including the AntiForgeryToken and ValidationSummary above it
<form id="frm" class="form-horizontal well"> // remove this and its corresponding closing tag