Create Submit Button for Table in Razor & MVC - c#

I am new to MVC and I am not sure where my problem is but having difficulty finding a challenge I am facing. My Save Button Posts a record but the columns are all null, it doesn't not post all the entry I filled out. I have been working on this for over two days now you are my hope.
Thank you.
<div >
<div style="margin-left:8px; margin-right:8px;" class="panel panel-primary ">
<div class="panel-heading">
#{
if (Model.Employees.id > 0) {
<h3 class="panel-title">Update Existing Employee: #Model.Employees.FirstName, #Model.Employees.LastName</h3>
} else if (Model.Employees.FirstName == null) {
<h3 class="panel-title">Add New Employee: </h3>
}
}
</div>
<table id="employee_form">
<tbody id="employees">
<tr class="panel-body">
<td class="form-group">
#using (Html.BeginForm("Save", "Employees")) {
<div class=" col-lg-4 ">
#Html.HiddenFor(e => e.Employees.id)
<ol class="row">
<li style="padding-top:25px;"><label for="FirstName" id="FirstName">First Name: </label><input class="form-control" type="text" value="#Model.Employees.FirstName" /></li>
<li ><label for="LastName" >Last Name: </label><input class="form-control" type="text" value="#Model.Employees.LastName" /></li>
<li ><label for="PhoneNumber" id="">Phone Number: </label><input class="form-control" type="text" value="#Model.Employees.PhoneNumber" /></li>
<li ><label for="Email" id="">Email: </label><input class="form-control" type="text" value="#Model.Employees.Email" /></li>
</ol>
</div>
<div class=" col-lg-4" style="">
<ol>
<li style="padding-top:25px;"><label for="providername" id="ProviderName"> Provider Name: </label><input style="float:right;" class="form-control" type="text" value="#Model.Employees.ProviderName" /></li>
<li><label for="OfficeAddress" id="">Address: </label><input class="form-control" type="text" value="#Model.Employees.OfficeAddress" /></li>
<li><label for="City" id="">City: </label><input class="form-control" type="text" value="#Model.Employees.City" /></li>
<li><label for="State" id="">State: </label><input class="form-control" type="text" value="#Model.Employees.State" /></li>
<li><label for="ZipCode" id="">Zip Code: </label><input class="form-control" type="text" value="#Model.Employees.ZipCode" /></li>
</ol>
</div>
<div class="col-lg-3 ">
<ol>
<li style="padding-top:25px;"><label for=" officefax" id="">Office Fax No.: </label><input class="form-control" type="text" value="#Model.Employees.OfficeFax" /></li>
<li><label for="OfficePhoneNumber" id="">Office Ph. No.: </label><input class="form-control" type="text" value="#Model.Employees.OfficePhoneNumber" /></li>
<li><label for="Notes1" >Notes</label><textarea class="form-control" value="#Model.Employees.Notes"></textarea></li>
</ol>
</div>
<div class="col-lg-12 row">
<button style="float:right;" type="submit" class="btn btn-info">Save</button>
</div>
}
<div class="col-lg-4">
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<hr />
And here is my controller action:
[HttpPost]
public ActionResult Save(Employees employees) {
if (!ModelState.IsValid) {
var employeeViewModel = new EmployeesViewModel
{
Employees = employees, EmployeeDetails = _Context.EmployeeDetails.ToList()
};
return View("EmployeeForm", employeeViewModel);
}
if (employees.id == 0) {
_Context.Employees.Add(employees);
} else {
var employeeInDb = _Context.Employees.Single(e => e.id == employees.id);
employeeInDb.FirstName = employees.FirstName;
employeeInDb.LastName = employees.LastName;
employeeInDb.Email = employees.Email;
employeeInDb.DoctorsName = employees.DoctorsName;
employeeInDb.ProviderName = employees.ProviderName;
employeeInDb.City = employees.City;
employeeInDb.State = employees.State;
employeeInDb.ZipCode = employees.ZipCode;
employeeInDb.OfficeAddress = employees.OfficeAddress;
employeeInDb.OfficePhoneNumber = employees.OfficePhoneNumber;
employeeInDb.OfficeFax = employees.OfficeFax;
employeeInDb.Notes = employees.Notes;
}
_Context.SaveChanges();
return RedirectToAction("Index", "Employees");
}

Your input tags don't have a name attribute, so they don't post back.
For example this tag:
<input class="form-control" type="text" value="#Model.Employees.LastName" />
Instead you should use
#Html.TextBoxFor(m=>m.Employees.LastName)
Or if you want to use the input tag directly you could just add the name
<input class="form-control" type="text" name="#Html.NameFor(m=>m.Employees.LastName)" value="#Model.Employees.LastName" />

You are doing it wrong, here's a simple example I can give you:
Assuming you have a model named Employee:
public class Employee
{
public int Id {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
public Employee() {}
}
And you have a view like this:
#model Employee
#using (Html.BeginForm("Save", "Employees"))
{
#Html.AntiForgeryToken()
#Html.LabelFor(m => m.FirstName)
#Html.TextBoxFor(m => m.FirstName)
#Html.LabelFor(m => m.LastName)
#Html.TextBoxFor(m => m.LastName)
<button type="submit">Save</button>
}
You should be able to do the get and post actions in your controller with something like this:
[HttpGet]
public ActionResult Save()
{
var employee = new Employee();
return View(employee);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(Empoyee employee)
{
if (!ModelState.IsValid)
{
//do whatever you want here
}
return View(employee);
}
I hope this helps.

Related

Search with multiple fields in asp.net core mvc

I create form where I get data from database using sql queries in asp.net core mvc. Now I want to search data with multiple fields like price, area, areaUnit . I am new to c# Kindly help me to search data and display. Data display in other div. In that div I make cards and get data from database using foreachloop.
MY view :
#model IEnumerable<eHouse.Models.RentModel>
<form>
<div class="wrap">
<div class="search">
<input type="text" class="searchTerm" style="width: 700px; color:#000000; text-align: left;" placeholder="Search Houses" onclick="filterfunction()">
<button type="submit" class="searchButton" >
<i class="fa fa-search"></i>
</button>
</div>
<div id="filter">
<select>
<option value="Kanal">Kanal</option>
<option value="Marla">Marla</option>
<option value="Square Feet">Square Feet</option>
<option value="Square Meter">Square Meter</option>
<option value="Square Yards">Square Yards</option>
</select>
<input type="text" placeholder="area" />
<input type="text" placeholder="price" />
</div>
</div>
</form>
<div class="property_information" >
#foreach (var item in Model)
{
<div class="home-info">
<span id="houseid">
</span>
<a href="#" class="home-images">
<img src="#item.pic1" />
</a>
<div class="home-data">
<div class="home-name">
<p>#item.tittle</p>
</div>
<div class="price">
<p>#item.price</p>
</div>
<div class="features">
<span>
#item.bedroom
</span>
<span>
#item.bathroom
</span>
<span>
2
</span>
</div>
<div class="desc">
#item.descrip
</div>
<div class="contact-save">
<a href="#" class="phone_number" id="favorite" onclick="Fav(this)" data-id="#item.id" >
<i class="fas fa-heart" style=" color: white;"></i>
</a>
<div class="popup" onclick="myFunction()">
<a href="tel:+928754756478" class="phone_number" onclick="call()">
</a>
</div>
<div class="popupmsg" onclick="myFunctionmsg()">
<a href="#" class="phone_number open_message" onclick="msg()">
</a>
</div>
<a href="#" class="phone_number" onclick="del(this)" data-id="#item.id">
<i class="fas fa-trash-alt" style=" color: white;"></i>
</a>
</div>
</div>
</div>
}
</div>
My Controller:
public IActionResult Rent(int PageNumber = 1)
{
var data = rdb.GetDataHouse();
var datas = rdb.GetDataHouse();
ViewBag.Data = datas.ToList().Take(6);
ViewBag.Totalpages = Math.Ceiling(data.Count()/6.0);
data = data.Skip((PageNumber - 1) * 6).Take(6).ToList();
return View(data);
}
Pass the filter data through a input submit in the form. You will need new viewModel with your data, input for post and filterList
You need something like this,
#model YourViewModel;
//Your form
<label asp-for="Input.Name"></label>
<select asp-for="Input.Name" asp-items="#(new SelectList(Model.SearchList))" class="form-control">
<option></option>
</select>
<span asp-validation-for="Input.Name" class="text-danger"></span>
<input type="submit" value="Search" class="btn btn-primary"/>
//your loop
#foreach (var item in Model.Data)
//Contoller
public IActionResult Rent(int PageNumber = 1, InputModel input)
{
var data = rdb.GetDataHouse();
var datas = rdb.GetDataHouse();
ViewBag.Data = datas.ToList().Take(6);
ViewBag.Totalpages = Math.Ceiling(data.Count()/6.0);
if(!string.InNullOrEmpty(input.Name))
{
data = data.Where(x => x.Name == input.Name).ToList();
}
data = data.Skip((PageNumber - 1) * 6).Take(6).ToList();
var viewModel = new YourViewModel
{
Data = data // data,
SearchList = your List<string>(), //for dropdown
Input = new YourInputModel(),
}
return View(viewModel);
}
//Input model
public class YourInputModel
{
public string Name { get; set; }
}
//View model
public class YourViewModel
{
public YourDataType Data{ get; set; }
public List<strings> SearchList { get; set; }
public YourInputModel Input { get; set; }
}
You also need some other things, which I hope you will handle

Model List returning as null from view to controller ASP.NET Core MVC

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.

Unable to bind data to the razor view even though the model is not null

Even though the model is not null the required html is not rendered. This is my razor view:
#model List<Product>
#{
ViewBag.Title = "Cart";
}
#for(int i=0;i<=Model.Count()-1;i++)
{
<p>foreach triggered</p>
var image = "~/images/" + Model[i].product_image_path;
<div class="row">
<div class="col">
<div class="row">
<div class="col-md-2">
<img src="#image" alt="No image" class="img-fluid" width="60" asp-append-version="true" />
</div>
<div class="col-md-4">
<div class="row">
<div class="col">
<p class="justify-content-md-start">#Model[i].ProductName</p>
</div>
</div>
<div class="row">
<div class="col">
<p>₹#Model[i].Price</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="row">
<div class="col-md-8">
#*change quantity button*#
<div class="input-group">
<button type="submit" class="btn btn-light"> - </button>
<input type="text" class="form-control" value="#Model[i].Quantity" readonly />
<button type="submit" class="btn btn-light"> + </button>
</div>
</div>
</div>
<br />
</div>
<div class="col-md-2">
<div class="row">
<div class="col">
<button class="btn btn-danger" type="button" id="button-minus">Remove</button>
</div>
</div>
</div>
</div>
</div>
</div>
}
Here is my get action method. This is basically retrieving the product from the models. I am returning an object of List<Product>. Trying to loop over it using for loop on razor view does not seem to work.
[HttpGet]
public IActionResult Cart()
{
var model = new CartProductViewModel();
var sessionId = HttpContext.Session.Id;
var allCartItems = context.cartItems;
var allProducts = context.products;
var currentCartItem = allCartItems.Where(p => p.Product.ProductId.Equals(sessionId)).Select(p=>p).ToList();
List<Product> products = new List<Product>();
foreach (var item in currentCartItem)
{
var id = item.Product.ProductId;
if (id is null) { return View("NotFound"); }
Product prod = allProducts.Where(p => p.ProductId.Equals(id)).Select(p=>p).Single();
products.Add(prod);
}
return View(products);
}

Checkbox always show False either it is True

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">

The id is missed when form is posted to controller

I am developing a mvc website.I have a table called member .this table has a controller and the controller has an edit method as you can see :
public ActionResult Edit()
{
int userId = _memberRepository.ReturnMemberIdByMobile(User.Identity.Name);
ViewBag.Edit = _memberRepository.FindById(userId).First();
return View();
}
[HttpPost]
public ActionResult Edit(Member value)
{
try
{
if (_memberRepository.Edit(value))
{
value.RegisteredDate = DateTime.Now;
_memberRepository.Save();
TempData["Success"] = "با موفقیت ویرایش شد ...";
string strLocation = HttpContext.Server.MapPath("~/Image/users");
if (value.ImgByte != null)
{
value.ImgByte.SaveAs(strLocation + #"\" + value.Id + ".jpg");
}
}
}
catch (Exception)
{
TempData["Error"] = "ویرایش نشد، لطفاً مجدداً تلاش نمایید";
}
return RedirectToAction("Edit");
}
The edit view is correctly work.the problem is when i post my view to edit controller .the id of member is changed to 0 it means it is missed.why ?and the value can't be edited.
#using DCL
#{
ViewBag.Title = "Edit";
Layout = "~/Areas/user/Views/Shared/_shared.cshtml";
Member membervalue = new Member();
membervalue = ViewBag.Edit;
}
#using (#Html.BeginForm("Edit", "User", FormMethod.Post,
new {id = "form", enctype = "multipart/form-data"}))
{
if (TempData["Error"] != null)
{
<div class="pad margin no-print">
<div class="callout callout-info" style="margin-bottom: 0 !important; background-color: #ea0000 !important; border-color: #d20000">
#TempData["Error"]
</div>
</div>
}
if (TempData["Information"] != null)
{
<div class="pad margin no-print">
<div class="callout callout-info" style="margin-bottom: 0 !important; background-color: orangered !important; border-color: red">
#TempData["Information"]
</div>
</div>
}
if (TempData["Success"] != null)
{
<div class="pad margin no-print">
<div class="callout callout-info" style="margin-bottom: 0 !important; background-color: #00A65A !important; border-color: #00925A">
#TempData["Success"]
</div>
</div>
}
<div class="row">
<!-- general form elements -->
<div class="col-xs-12">
<div class="box">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">حساب کاربری</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<div class="box-body">
<div class="col-lg-7">
<div class="input-group">
<label for="Name">نام</label>
<input class="form-control" id="Name" name="Name" type="text" value="#membervalue.Name">
</div>
<div class="input-group">
<label for="family">نام خانوادگی</label>
<input class="form-control" id="family" name="family" type="text" value="#membervalue.Family">
</div>
<div class="input-group">
<label for="mobile">موبایل</label>
<input class="form-control" id="mobile" name="mobile" type="text" value="#membervalue.Mobile">
</div>
<div class="input-group">
<label for="password">رمز عبور</label>
<input class="form-control" id="password" name="password" type="password" value="#membervalue.Password">
</div>
<div class="input-group">
<label for="Email">ایمیل</label>
<input class="form-control" id="Email" name="Email" type="text" value="#membervalue.Email">
</div>
<div class="form-group">
<label for="ImgByte">عکس </label>
<input id="ImgByte" name="ImgByte" type="file">
</div>
<input type="hidden" id="Id" name="id" value="#membervalue.Id">
</div>
</div>
<!-- /.box-body -->
</div>
</div>
</div>
<!-- /.box -->
</div>
<div class="row" style="margin: 0; margin-bottom: 20px">
<div class="box-footer" style="direction: ltr">
<button type="submit" class="btn btn-info">ویرایش</button>
<a class="btn btn-gray" href="#Url.Action("Index", "Home", null)">انصراف</a>
</div>
</div>
}
Instead of using the viewbag for your model you should pass in the model as a strongly typed object. You can do this with the following change in the Action. Then in your view define the model at the top and you can use it throughout the code.
You will also need a #Html.HiddenFor tag for your id. Now it is no longer possible (without a compile time exception that is) to create a type-o. On your previous code maybe you cased Id incorrectly which would cause it not to be populated OR maybe the form field name was not cased correctly. This takes all those manual errors out of the equation.
public ActionResult Edit()
{
int userId = _memberRepository.ReturnMemberIdByMobile(User.Identity.Name);
var model = _memberRepository.FindById(userId).First();
return View(model); // pass this in as the model, do not use viewbag
}
View
#model = Member #* namespace qualified type *#
#*... editor code *#
#Html.HiddenFor(x => x.Id)
#Html.TextboxFor(x => x.Name) #* do this instead of manual input *#
I ran your code, and there is no mistake in it. Id is passed correctly to Edit (post) action. The only reason it can be empty in the code that you show is that FindById returned entity without Id property set.

Categories

Resources