my list variable array missing after click button - asp.net-mvc

I don't have DB, instead DB I have to list array, I have a table, and when I want Edit details of Driver, I click 'edit', after that display change to page with details, after that I can change details and click save button, my problem that after clicking button 'save', my array list miss, I not very good in MVC, but I try my best! if somebody sees what I do wrong, please tell me and explain, thank you
that my controller
public class DriverTaxiController : Controller
{
static List<Drivers> Driver = new List<Drivers>();
public static int numLine = -1;
// GET: DriverTaxi
public ActionResult List()
{
Driver.Add(new Drivers() { Line = 1, NumberLicens = "123456", FirstName = "Evgeny", LastName = "Ryvkin", PhoneNumber = "0546819725", StartWork = "12/10/17", DateCheckEyes = "13/10/17"});
Driver.Add(new Drivers() { Line = 2, NumberLicens = "123457", FirstName = "Moshe", LastName = "Kohen", PhoneNumber = "0546819725", StartWork = "12/10/17", DateCheckEyes = "13/10/17" });
Driver.Add(new Drivers() { Line = 3, NumberLicens = "123458", FirstName = "Dana", LastName = "Multy", PhoneNumber = "0546819725", StartWork = "12/10/17", DateCheckEyes = "13/10/17" });
ViewBag.Drivers = Driver;
return View();
}
public ActionResult MyAction(int id=0)
{
for(int i = 0; i < Driver.Count; i++)
{
if(Driver[i].Line == id)
{
ViewBag.nl = Driver[i].NumberLicens;
ViewBag.fn = Driver[i].FirstName;
ViewBag.ln = Driver[i].LastName;
ViewBag.phone = Driver[i].PhoneNumber;
ViewBag.start = Driver[i].StartWork;
ViewBag.eye = Driver[i].DateCheckEyes;
ViewBag.line = Driver[i].Line;
}
}
numLine = id;
return View();
}
[HttpPost]
public ActionResult Update()
{
if (ModelState.IsValid)
{
numLine--;
Driver[numLine].NumberLicens = Request.Form["NumberLicens"];
Driver[numLine].FirstName = Request.Form["FirstName"];
Driver[numLine].LastName = Request.Form["LastName"];
Driver[numLine].PhoneNumber = Request.Form["PhoneNumber"];
Driver[numLine].StartWork = Request.Form["StartWork"];
Driver[numLine].DateCheckEyes = Request.Form["DateCheckEyes"];
return View("List2");
}
else
{
return View("MyAction");
}
}
that my View Edit, when I click the button, my parameters not saved in my list, I don't understand why
#using (Html.BeginForm("Update", "DriverTaxi"))
{
#Html.TextBoxFor(Model => Model.NumberLicens, new { #Value = #ViewBag.nl }) #Html.ValidationMessageFor(x => x.NumberLicens)
<br />
#Html.TextBoxFor(Model => Model.FirstName, new { #Value = #ViewBag.fn })
<br />
#Html.TextBoxFor(Model => Model.LastName, new { #Value = #ViewBag.ln })
<br />
#Html.TextBoxFor(Model => Model.PhoneNumber, new { #Value = #ViewBag.phone })
<br />
#Html.TextBoxFor(Model => Model.StartWork, new { #Value = #ViewBag.start })
<br />
#Html.TextBoxFor(Model => Model.DateCheckEyes, new { #Value = #ViewBag.eye })
<br />
#Html.HiddenFor(Model => Model.Line)
<input type="submit" value="Save" />
#Html.ValidationSummary()
}
that my Table
<table class="table table-bordered table-responsive table-hover">
<tr>
<th>No.</th>
<th>Number Licens</th>
<th>Full Name</th>
<th>Phone Number</th>
<th>Start Work</th>
<th>Date Cheking the Eyes</th>
<th>Address</th>
<th>Email</th>
<th>Edit</th>
<th>Delete</th>
</tr>
#foreach (Drivers p in ViewBag.Drivers)
{
<tr>
<td>#p.Line</td>
<td>#p.NumberLicens</td>
<td>#p.FirstName #p.LastName </td>
<td>#p.PhoneNumber</td>
<td>#p.StartWork</td>
<td>#p.DateCheckEyes</td>
<td>
#Html.ActionLink("Edit", "MyAction", "DriverTaxi", new { id = p.Line }, null)
</td>
<td>addres</td>
<td>email</td>
<td><input id="Button2" type="submit" value="Delete" name="#p.NumberLicens" /></td>
</tr>
}`enter code here`
and that my error
enter image description here

Just add your ViewBag assignment to each of your actions that render view. Something like this:
public ActionResult MyAction(int id=0)
{
for(int i = 0; i < Driver.Count; i++)
{
if(Driver[i].Line == id)
{
ViewBag.nl = Driver[i].NumberLicens;
ViewBag.fn = Driver[i].FirstName;
ViewBag.ln = Driver[i].LastName;
ViewBag.phone = Driver[i].PhoneNumber;
ViewBag.start = Driver[i].StartWork;
ViewBag.eye = Driver[i].DateCheckEyes;
ViewBag.line = Driver[i].Line;
}
}
numLine = id;
ViewBag.Drivers = Driver; //TODO
return View();
}
[HttpPost]
public ActionResult Update()
{
if (ModelState.IsValid)
{
numLine--;
Driver[numLine].NumberLicens = Request.Form["NumberLicens"];
Driver[numLine].FirstName = Request.Form["FirstName"];
Driver[numLine].LastName = Request.Form["LastName"];
Driver[numLine].PhoneNumber = Request.Form["PhoneNumber"];
Driver[numLine].StartWork = Request.Form["StartWork"];
Driver[numLine].DateCheckEyes = Request.Form["DateCheckEyes"];
ViewBag.Drivers = Driver; //TODO
return View("List2");
}
else
{
ViewBag.Drivers = Driver; //TODO
return View("MyAction");
}
}

Related

How to Bring Child's Name to List?

enter image description hereI intend to return the name of the child with the vaccines already administered.
what happens is that it does not return anything to me, since if I call the Id it returns the Id of the Child
Model VacinacaoIndexData
using GestCentros.Models;
using System.Collections.Generic;
namespace GestCentros.ViewModels
{
public class VacinacaoIndexData
{
public IEnumerable<Vacinacao> Vacinacoes { get; set; }
public IEnumerable<Vacina> Vacinas { get; set; }
public IEnumerable<Enrollment> Enrollments { get; set; }
}
}
Controler
public ActionResult Index(int? id, int? Idvacina)
{
var user = db.Users.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
if (user == null)
{
return RedirectToAction("Index", "Home");
}
var viewModel = new VacinacaoIndexData();
viewModel.Vacinacoes = db.Vacinacao
.Include(v => v.Vacinas)
.Include(v => v.Crianca)
.Where(c => c.IdCentro == user.IdCentro);
if (id != null)
{
ViewBag.IdVacinacao = id.Value;
viewModel.Vacinas = viewModel.Vacinacoes
.Single(i => i.IdVacinacao == id.Value).Vacinas;
}
if (Idvacina == null) return View(viewModel);
ViewBag.IdVacina = Idvacina.Value;
// Lazy loading
viewModel.Enrollments = viewModel.Vacinas.Single(x => x.IdVacina == Idvacina).Enrollments;
// Explicit loading
Vacina selectedVacina = viewModel.Vacinas.Single(x => x.IdVacina == Idvacina);
db.Entry(selectedVacina).Collection(x => x.Enrollments).Load();
foreach (var enrollment in selectedVacina.Enrollments)
{
db.Entry(enrollment).Reference(x => x.Centro).Load();
}
viewModel.Enrollments = selectedVacina.Enrollments;
return View(viewModel);
}
In the Field Name I would like to Show Child Name, but it does not return anything
#model GestCentros.ViewModels.VacinacaoIndexData
#{
ViewBag.Title = "Index";
}
<h2 class="text-center">Lista de Crianças Vacinadas</h2>
<table class="table">
<tr>
<th>Nome</th>
<th>Data Vacinação</th>
<th>Vacinas</th>
<th>Operações</th>
</tr>
#foreach (var item in Model.Vacinacoes)
{
string selectedRow = "";
if (item.IdVacinacao == ViewBag.IdVacinacao)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.DisplayFor(model => item.Crianca.Nome)
</td>
<td>
#item.DataVacina.ToString("dd/MM/yyyy")
</td>
<td>
#{
foreach (var vacina in item.Vacinas)
{
#: #vacina.Nome <br />
}
}
</td>
</tr>
}
</table>
#if (Model.Vacinas != null)
{
<h3>Vacinas Ministradas na Campanha</h3>
<table class="table">
<tr>
<th>Operações</th>
<th>Vacina</th>
</tr>
#foreach (var item in Model.Vacinas)
{
var selectedRow = "";
if (item.IdVacina == ViewBag.IdVacina)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.ActionLink("Selecionar", "Index", new { IdVacina = item.IdVacina }, new { #class = "btn btn-sm btn-secundary" })
| #Html.ActionLink("Voltar a Lista", "Index", new { }, new { #class = "btn btn-sm btn-default" })
</td>
<td>
#item.Nome
</td>
</tr>
}
</table>
}
#if (Model.Enrollments != null)
{
<h3>
Students Enrolled in Selected Course
</h3>
<table class="table">
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
#foreach (var item in Model.Enrollments)
{
<tr>
<td>
#item.Centro.Name
</td>
<td>
#Html.DisplayFor(modelItem => item.Grade)
</td>
</tr>
}
</table>
}

dropdown load on selection of other dropdown

I have the dropdown trigger an ajax post that sends the selected value of country dropdown .
model class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVC_4___A_Registration_Form.Models
{
public class ModelServices
{
private readonly MyCompanyEntities entities = new MyCompanyEntities();
public IEnumerable<Country> GetCountryList()
{
return entities.Countries.ToList();
}
public IEnumerable<countryState> GetStateByCountry(int CountryID)
{
return entities.countryStates.Where(s => s.CountryId == CountryID).ToList();
}
public IList<EmployeeRegInfo> GetAllEmployeeList()
{
var myQuery = (from e in entities.Employees
join c in entities.Countries on e.Country equals c.CountryId
join s in entities.countryStates on e.State equals s.StateId
select new EmployeeRegInfo()
{
Id = e.Id,
Emp_ID = e.Emp_ID,
Dept = e.Dept,
Name = e.Name,
CountryName = c.County,
StateName = s.State,
City = e.City,
Mobile = e.Mobile
});
return myQuery.ToList();
}
public bool IsEmpAlreadyExist(string EMP_CODE)
{
bool IsRecordExist = false;
var result = (from t in entities.Employees
where t.Emp_ID == EMP_CODE
select t).SingleOrDefault();
if (result != null)
{
IsRecordExist = true;
}
return IsRecordExist;
}
public void AddNewEmployee(Employee emp)
{
entities.Employees.Add(emp);
entities.SaveChanges();
}
}
}
create.cshtml
#model MVC_4___A_Registration_Form.Models.EmployeeRegInfo
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#ViewBag.ErrorMsg
<table>
<tr>
<td>
#Html.LabelFor(model => model.Emp_ID)
</td>
<td>#Html.EditorFor(model => model.Emp_ID)
#Html.ValidationMessageFor(model => model.Emp_ID)</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Name)
</td>
<td>#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.Dept)
</td>
<td>#Html.EditorFor(model => model.Dept)
#Html.ValidationMessageFor(model => model.Dept)</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Country)</td>
<td>#Html.DropDownList("Country", ViewBag.Country as SelectList, new { Styles = "width:300px" })</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.State)
</td>
<td>
<select id="State" name="State" style="width: 200px"></select>
#Html.ValidationMessageFor(model => model.State)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.City)</td>
<td>#Html.EditorFor(model => model.City)
#Html.ValidationMessageFor(model => model.City)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Mobile)</td>
<td>#Html.EditorFor(model => model.Mobile)
#Html.ValidationMessageFor(model => model.Mobile)
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Add Employee" /></td>
</tr>
</table>
}
<script type="text/javascript">
$(document).ready(function () {
$("#Country").change(function () {
var url = "/ManageEmployee/GetStatesByCountry";
var countryID = $("#Country").val();
$.post(url, { countryID: countryID }, function (data) {
$("#State").empty();
var items;
$.each(data, function (i, states) {
items += "<option value=" + states.StateId + ">" + states.State + "</option>";
});
$("#State").html(items);
});
});
});
</script>
controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_4___A_Registration_Form.Models;
namespace MVC_4___A_Registration_Form.Controllers
{
public class ManageEmployeeController : Controller
{
ModelServices model = new ModelServices();
//
// GET: /ManageEmployee/
public ActionResult Index()
{
IList<EmployeeRegInfo> empList = new List<EmployeeRegInfo>();
empList = model.GetAllEmployeeList();
return View(empList);
}
public ActionResult Create()
{
IEnumerable<Country> country;
country = model.GetCountryList();
ViewBag.Country = new SelectList(country, "CountryId", "County", "CountryId");
return View();
}
[HttpPost]
public ActionResult Create(FormCollection collection)
{
bool checkEmpCodeExist = false;
checkEmpCodeExist = model.IsEmpAlreadyExist(collection["Emp_ID"]);
if (!checkEmpCodeExist)
{
try
{
Employee emp = new Employee();
emp.Emp_ID = collection["Emp_ID"];
emp.Name = collection["Name"];
emp.Dept = collection["Dept"];
emp.Country = Convert.ToInt32(collection["Country"]);
emp.State = Convert.ToInt32(collection["State"]);
emp.City = collection["City"];
emp.Mobile = collection["Mobile"];
model.AddNewEmployee(emp);
return RedirectToAction("Index");
}
catch (Exception ex)
{
return RedirectToAction("Create");
}
}
else
{
ViewBag.ErrorMsg = "Employee Code Already Exist";
return RedirectToAction("Create");
}
}
public JsonResult GetStatesByCountry(int id)
{
var states = model.GetStateByCountry(id);
return Json(states, JsonRequestBehavior.AllowGet);
}
}
}
I want to load state dropdown on selection of country dropdown.But i am unable to do this.
Please help to load state dropdown on selection of country dropdown.
I want to load state dropdown on selection of country dropdown.But i am unable to do this.
Please help to load state dropdown on selection of country dropdown.
Hey I got the answer
some change in ajax code and controller
$(document).ready(function () {
$("#Country").change(function () {
var url = "/ManageEmployee/GetStatesByCountry";
var countryID = $("#Country").val();
$.ajax({
url: url,
data: { id: countryID },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#State").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
});
[HttpPost]
public JsonResult GetStatesByCountry(string id)
{
int ids = Convert.ToInt32(id);
var states = model.GetStateByCountry(ids);
SelectList obgcity = new SelectList(states, "StateId", "State", 0);
return Json(obgcity);
}

How to sort a Grid using Viewmodel not ViewBag?

I have my code working and sorting correctly but I am using ViewBag to do so. I would like to clean up my code and use ViewModel instead to sort my grid but I'm stumped in how to do so. Any help would be greatly appreciated. Thank you.
Model
public partial class Asset
{
public int AssetKey { get; set; }
public int ProductKey { get; set; }
public string InventoryOwner { get; set; }
public string SerialNumber { get; set; }
Controller
public class InventoryManagementController : Controller
{
private Orders db = new Orders();
public ActionResult Index(int? AssetNum, string keyword, string sortOrder, string currentFilter, int? page)
{
ViewBag.OwnerSort = sortOrder == "owner_asce" ? "owner_desc" : "owner_asce";
ViewBag.AssetSort = sortOrder == "asset_asce" ? "asset_desc" : "asset_asce";
ViewBag.SerialSort = sortOrder == "serialnum_asce" ? "serialnum_desc" : "serialnum_asce";
ViewBag.ProductSort = sortOrder == "product_asce" ? "product_desc" : "product_asce";
ViewBag.Keyword = keyword;
var records = from s in db.Assets select s;
string AssetNums = AssetNum.ToString();
if (keyword != null)
{
page = 1;
}
else
{
keyword = currentFilter;
}
ViewBag.CurrentFilter = keyword;
switch (sortOrder)
{
case "asset_asce":
records = records.OrderBy(s => s.AssetKey);
break;
case "asset_desc":
records = records.OrderByDescending(s => s.AssetKey);
break;
case "serialnum_asce":
records = records.OrderBy(s => s.SerialNumber);
break;
case "serialnum_desc":
records = records.OrderByDescending(s => s.SerialNumber);
break;
case "product_asce":
records = records.OrderBy(s => s.Product.ProductName);
break;
case "product_desc":
records = records.OrderByDescending(s => s.Product.ProductName);
break;
case "owner_asce":
records = records.OrderBy(s => s.InventoryOwner);
break;
case "owner_desc":
records = records.OrderByDescending(s => s.InventoryOwner);
break;
int pageSize = 25; //Number of Records
int pageNumber = (page ?? 1);
return View(records.ToPagedList(pageNumber, pageSize));
//return View(assets.ToList());
}
View
#model PagedList.IPagedList<OrderDB.Models.Asset>
#using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Inventory HomePage";
}
<!DOCTYPE html>
<title>Index</title>
<br />
<h2>Inventory</h2>
<table class="table" border="1">
<tr>
<th>
#Html.ActionLink("Asset Tag", "Index", new { sortOrder = ViewBag.AssetSort, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("Serial Number", "Index", new { sortOrder = ViewBag.SerialSort, keyword = ViewBag.Keyword, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("Product", "Index", new { sortOrder = ViewBag.ProductSort, keyword = ViewBag.Keyword, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("Inventory Owner", "Index", new { sortOrder = ViewBag.OwnerSort, keyword = ViewBag.Keyword, currentFilter = ViewBag.CurrentFilter })
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.ActionLink(item.AssetKey.ToString(), "Details", new { id = item.AssetKey })
</td>
<td>
#Html.DisplayFor(modelItem => item.SerialNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.Product.ProductName)
</td>
<td>
#Html.DisplayFor(modelItem => item.InventoryOwner)
</td>
</tr>
}
</table>
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

Display List return from a controller to a table in view ASP.NET MVC4

I have a function in my controller class, it return a list of data, I want to display it in table structure in my view page.
i have tried the following code but it shows some error
"Class does not contain definition of GetEnumerator"
Controller
public ActionResult data(Message msg,IEnumerable<sample> dept)
{
dbconnection db = new dbconnection();
sample s = new sample();
SqlConnection con = new SqlConnection(db.GetconString());
DataTable dt;
List<examplemvc1.Models.sample> datatable = new List<sample>();
dt = db.BuildDT("select * from MVCsample");
foreach (DataRow row in dt.Rows)
{
s.FirstName = Convert.ToString(row["First Name"]);
s.LastName = Convert.ToString(row["Last Name"]);
s.Address = Convert.ToString(row["Address"]);
s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
s.Location = Convert.ToString(row["Location"]);
datatable.Add(s);
dept = datatable;
}
ViewBag.tabledata = dept;
return View(dept) ;
}
Model
public class sample
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string PhoneNumber { get; set; }
public string Location { get; set; }
public string tabledata { get; set; }
}
public class Message
{
public IEnumerable<sample> sampleList { get; set; }
public string MessageText { get; set; }
public string MessageFrom { get; set; }
}
View
#model examplemvc1.Models.sample
#foreach (var data in Model)
{
<table><tr><td>#data.FirstName</td></tr></table>
}
UPDATE
this is how my entire view looks like
#model List<examplemvc1.Models.sample>
#{
ViewBag.Title = "Registration Form";
}
<head>
<script type="text/javascript" src="../../Scripts/jquery-1.7.1.min.js"></script>
<link href="../../Style/sample.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/samplescript.js" type="text/javascript"></script>
</head>
<h2>
Registration Form </h2>
<body>
<table>
<tr>
<th>
First Name
</th>
</tr>
#foreach (var data in Model)
{
<tr><td>#data.FirstName</td></tr>
}
</table>
#using (Html.BeginForm())
{
<table id="table1">
<tr>
<td>
#Html.Label("Enter FirstName", new { #class = "standard_label_style" })
</td>
<td>
#Html.TextBoxFor(a => a.FirstName, new { #class = "class1", title = "Enter FirstName", id = "NameBox", placeholder = "Enter name", onkeydown = "return TextField(event)" })
<span class="errorMessage"></span>
#if (!ViewData.ModelState.IsValid)
{
<span class="field-validation-error">
#ViewData.ModelState["FirstName"].Errors[0].ErrorMessage</span>
}
</td>
</tr>
<tr>
<td>
#Html.Label("Enter LastName", new { #class = "standard_label_style" })
</td>
<td>
#Html.TextBoxFor(a => a.LastName, new { #class = "class1", placeholder = "Enter name", id = "LastNameBox", title = "Enter Lastname", onkeydown = "return TextField(event); " })
<span class="errorMessage"></span>
</td>
</tr>
<tr>
<td>
#Html.Label("Enter Address", new { #class = "standard_label_style" })
</td>
<td>
#Html.TextBoxFor(a => a.Address, new { #class = "class1", id = "AddressBox", placeholder = "Enter name", title = "Enter Address" })
<span class="errorMessage"></span>
</td>
</tr>
<tr>
<td>
#Html.Label("Enter PhoneNumber", new { #class = "standard_label_style" })
</td>
<td>
#Html.TextBoxFor(a => a.PhoneNumber, new { #class = "class1", id = "PhoneBox", placeholder = "Enter name", title = "Enter Phonenumber", onkeydown = "return ValidateNumber(event);" })
<span class="errorMessage"></span>
</td>
</tr>
<tr>
<td>
#Html.Label("Enter Location", new { #class = "standard_label_style" })
</td><td>
#Html.TextBoxFor(a => a.Location, new { #class = "class1", id = "LocationBox", placeholder = "Enter name", title = "Enter Location" })
<span class="errorMessage"></span>
</td>
</tr>
</table>
<input type="button" id="btnSave" value="Register"/>
<input type="button" value="Clear"/>
<input type="button" id="Tabledata" value="Tabledata"/>
<div id="div1"></div>
#*#Html.ValidationSummary()*#
<script type="text/javascript">
function ValidateNumber(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
};
function TextField(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (charCode > 31 && (charCode < 48 || charCode > 56)) {
return true;
}
else if (charCode == 8 || charCode == 9) {
return true;
}
return false
};
</script>
}
</body>
Error is shown in my view code, actually I don't know how to get that values in view page. I am newbie in mvc. Please help me to solve this. Any help will be greatly appreciated.
"Update"
I have solved My problem with the help of Stackoverflow Below is my correctcode
Controller
public ActionResult data()
{
SomeViewModel model = new SomeViewModel();
dbconnection db = new dbconnection();
SqlConnection con = new SqlConnection(db.GetconString());
DataTable dt = db.BuildDT("select * from MVCsample");
foreach (DataRow row in dt.Rows)
{
sample s = new sample();
s.FirstName = Convert.ToString(row["First Name"]);
s.LastName = Convert.ToString(row["Last Name"]);
s.Address = Convert.ToString(row["Address"]);
s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
s.Location = Convert.ToString(row["Location"]);
model.samples.Add(s);
}
return View(model);
}
Model
namespace examplemvc1.Models
{
public class sample
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string PhoneNumber { get; set; }
public string Location { get; set; }
public string tabledata { get; set; }
}
public class Message
{
public IEnumerable<sample> sampleList { get; set; }
public string MessageText { get; set; }
public string MessageFrom { get; set; }
}
public class SomeViewModel
{
public SomeViewModel()
{
samples = new List<sample>();
sample = new sample();
}
public List<sample> samples { get; set; }
public sample sample { get; set; }
}
}
view
#model examplemvc1.Models.SomeViewModel
//................
#foreach (var data in Model.samples)
{
<tr><td>#data.FirstName</td>
<td>#data.LastName</td>
<td>#data.Address</td>
<td>#data.PhoneNumber</td>
<td>#data.Location</td></tr>
}
</table>
Just look at Stephen Muecke's Answer below he has explained the context very clearly
You view is displaying both a list of sample and what appears t be a form for a new sample. Start by creating a view model to represent what you want to display/edit
public class SampleVM
{
public SampleVM
{
SampleCollection = new List<sample>
}
public List<sample> SampleCollection { get; set; }
public sample NewSample { get; set; }
}
In your controller modify the code to
public ActionResult data()
{
SampleVM model = new SampleVM();
dbconnection db = new dbconnection();
SqlConnection con = new SqlConnection(db.GetconString());
DataTable dt = db.BuildDT("select * from MVCsample");
foreach (DataRow row in dt.Rows)
{
sample s = new sample();
s.FirstName = Convert.ToString(row["First Name"]);
s.LastName = Convert.ToString(row["Last Name"]);
s.Address = Convert.ToString(row["Address"]);
s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
s.Location = Convert.ToString(row["Location"]);
model.SampleCollection.Add(s);
}
return View(model);
}
Notes:
Remove the parameters from the GET method. Apart from the fact you
don't use them so they are pointless, even if you were to try and
pass those objects to the method, binding would fail and the
collections would be null (and if you were to construct the correct
query string to make it work, it would be so long it would almost
certainly throw an exception)
You need to initialize a new sample inside the foreach loop
(your code only initialized one object, and each loop updated its
properties to the current row, so you would end up with multiple
reference of the same object, all matching the values of the last
row in your table)
There is no need to pass the model as a ViewBag property (its
already passed to the view using return View(model);
And modify your view to
#model SampleVM
....
<table>
#foreach(var sample in Model.SampleCollection)
<tr>
<td>#sample .FirstName</td>
</tr>
}
</table>
#Html.BeginForm())
{
#Html.LabelFor(m => m.NewSample.FirstName, "Enter FirstName", new { #class = "standard_label_style" })
#Html.TextBoxFor(m => m.NewSample.FirstName, #class = "class1", placeholder = "Enter name", title = "Enter Lastname")
#Html.ValidationMessageFor(m => m.NewSample.FirstName)
}
....
<input type="submit" id="btnSave" value="Register"/>
Notes:
A label element if for associating the element with a control. Your
usage generates <label for="Enter_FirstName"> but you dont have a
control with id="Enter_FirstName". Preferable you should have
[Display(Name = "Enter FirstName")] on the property, but otherwise
use the strongly types helper
Use #Html.ValidationMessageFor() to render ModelState errors,
although in your case all you properties are strings and you don't
have any validation attributes so there will never be any errors, so
its a bit pointless
The html helpers generate an id attribute. There is rarely a need
to overwrite it. Stop polluting your markup with behavior and learn
to use Unobtrusive Javascript
Your form did not contain a submit button
Problem is your model is of Type examplemvc1.Models.sample while you have to pass object of List<examplemvc1.Models.sample> to view:
return View(datatable) ;
Your action:
List <examplemvc1.Models.sample> datatable = new List<sample>();
dt = db.BuildDT("select * from MVCsample");
foreach (DataRow row in dt.Rows)
{
s.FirstName = Convert.ToString(row["First Name"]);
s.LastName = Convert.ToString(row["Last Name"]);
s.Address = Convert.ToString(row["Address"]);
s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
s.Location = Convert.ToString(row["Location"]);
datatable.Add(s);
}
return View(datatable); // passing list to view
and in View set model to List<examplemvc1.Models.sample>:
#model List<examplemvc1.Models.sample>
and now iterate the way you are doing:
<table>
<thead>
<tr><th>First Name</th></tr>
</thead>
<tbody>
#foreach (var data in Model)
{
<tr><td>#data.FirstName</td></tr>
}
</tbody>
</table>
Here problem is with your model directive.
It should be
#model IEnumerable<examplemvc1.Models.sample>
instead of
#model examplemvc1.Models.sample
Note: You are making assignment few times like dept = datatable; instead you can update the code like this.
public ActionResult data(Message msg,IEnumerable<sample> dept)
{
dbconnection db = new dbconnection();
sample s = new sample();
SqlConnection con = new SqlConnection(db.GetconString());
DataTable dt;
List <examplemvc1.Models.sample> datatable = new List<sample>();
dt = db.BuildDT("select * from MVCsample");
foreach (DataRow row in dt.Rows)
{
s.FirstName = Convert.ToString(row["First Name"]);
s.LastName = Convert.ToString(row["Last Name"]);
s.Address = Convert.ToString(row["Address"]);
s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
s.Location = Convert.ToString(row["Location"]);
datatable.Add(s);
//dept = datatable;
}
ViewBag.tabledata = datatable;
return View(datatable) ;
}
Update
In such a case you need to create viewmodel first and pass his instance there as model.
public class SomeViewModel
{
public SomeViewModel()
{
samples = new List<sample>();
sample = new sample();
}
public List<sample> samples {get; set;}
public sample sample {get; set;}
}
and in model declaration
#model namespace.SomeViewModel
and then in controller like following.
public ActionResult data(Message msg,IEnumerable<sample> dept)
{
dbconnection db = new dbconnection();
sample s = new sample();
SqlConnection con = new SqlConnection(db.GetconString());
DataTable dt;
List<examplemvc1.Models.sample> datatable = new List<sample>();
dt = db.BuildDT("select * from MVCsample");
foreach (DataRow row in dt.Rows)
{
s.FirstName = Convert.ToString(row["First Name"]);
s.LastName = Convert.ToString(row["Last Name"]);
s.Address = Convert.ToString(row["Address"]);
s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
s.Location = Convert.ToString(row["Location"]);
datatable.Add(s);
dept = datatable;
}
ViewBag.tabledata = dept;
SomeViewModel vm = new SomeViewModel();
vm.samples = datatable;
vm.sample = //somesample instance here you want to edit.
return View(vm) ;
}
and in view you will get the instance of vm iterate through vm.samples
#foreach (var data in Model.samples)
{
<tr><td>#data.FirstName</td></tr>
}
and in the rest of view do something like this:
#Html.TextBoxFor(a => a.sample.FirstName, new { #class = "class1", title =
"Enter FirstName", id = "NameBox", placeholder = "Enter name", onkeydown =
"return TextField(event)" })

ModelState.IsValid is false during my post

This is my controller:
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EMail(SendMailData objModelMail, HttpPostedFileBase fileUploader,SendMailData smd)
{
//string Emailid = smd.To;
//TryUpdateModel<SendMailData>(smd);
//var result = new List<ValidationResult>();
//var Context = new ValidationContext(ModelState, null, null);
//var errors = ModelState.Where(v => v.Value.Errors.Any());
if (ModelState.IsValid)
{
string from = "MYMAILID";
using (MailMessage mail = new MailMessage(from, objModelMail.To))
{
mail.Subject = objModelMail.Subject;
mail.Body = objModelMail.Body;
if (fileUploader != null)
{
string Filename = Path.GetFileName(fileUploader.FileName);
mail.Attachments.Add(new Attachment(fileUploader.InputStream, Filename));
}
//mail.To.Add(new MailAddress(eMailBox.Text));
// mail.To.Add(objModelMail.To);
//mail.From = new MailAddress(objModelMail.From);
//mail.Subject = objModelMail.Subject;
//string body = objModelMail.Body;
//mail.Body = body;
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient("127.0.0.1", 25);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("MYMAILID", "PASSWORD",from);
smtp.Port = 587;
smtp.ServicePoint.MaxIdleTime = 1;
smtp.Host = "smtp.gmail.com";
smtp.Send(mail);
ViewBag.message = "Send";
mail.Dispose();
return View("EMail", objModelMail);
}
}
else
{
return View();
}
}
This is my model:
public class SendMailData
{
[Required(ErrorMessage = "You Can't Leave This Empty")]
[RegularExpression(#"^(([a-zA-Z0-9_'+*$%\^&!\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9:]{2,7})([,;]\W?(?!$))?)+$", ErrorMessage = "Please enter correct email address")]
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
This is my View:
#model SampleUniversity1.Models.SendMailData
#{
ViewBag.Title = "EMail";
}
<script src="~/Scripts/jquery-1.7.1.min.js">
</script>
<script type="text/javascript">
if ('#ViewBag.message' == 'Send') {
alert("Email Sended Successfully");
}
</script>
<h2>Mail</h2>
<fieldset>
<legend>
Send Mail
</legend>
#using (Html.BeginForm("EMail", "Student", FormMethod.Post, new { #id = "form1", #enctype = "multipart/form-data" }))
{
#*#Html.AntiForgeryToken();*#
#Html.ValidationSummary(true)
<input type="submit" value="Send" style="width: 100px;" />
<table>
<tr>
<td>
To
</td>
<td>
#Html.TextAreaFor(x => x.To)
#Html.ValidationMessageFor(x => x.To)
</td>
</tr>
<tr>
<td>
Subject
</td>
<td>
#Html.TextAreaFor(x => x.Subject)
</td>
</tr>
<tr>
<td>
Attachment
</td>
<td>
<input type="file" name="fileUploader" />
</td>
</tr>
<tr>
<td>
Body
</td>
<td>
#Html.TextAreaFor(x => x.Body)
</td>
</tr>
<tr>
<td></td>
</tr>
</table>
}
</fieldset>
When I enter all the values correct it will display no error only else part is processing
else part is execute ModelState.IsValid is false.
You have a RequiredAttribute on the From property, but I can't see any input for it in you view, so it will be null and ModelState.IsValid() will be false

Resources