ModelState.IsValid is false during my post - asp.net-mvc

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

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

my list variable array missing after click button

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");
}
}

How to return data from model in textfields with Ajax call?

I am using asp.net mvc
And I have a login model with three fields:
-baliecode
-username
-password
So every balie code correspondents with a username and password.
And now I try to get the username and password in the texfields if a user has entered a baliecode an press TAB.
The action method looks likes this:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetLogindetails(V_LoginModel_BalieUser model)
{
ISalesPersonProfile salesAgent99 = CommerceFrameworkBase.SalesPersons.GetSalesPerson("HD");
if (model.BalieCode == salesAgent99.Id)
{
model.UserName = salesAgent99.Email;
}
return Json(model);
}
The models looks like this:
public class V_LoginModel_BalieUser : LoginModel
{
public string BalieCode { get; set; }
}
//
// Summary:
// A model to login into the webshop.
public class LoginModel
{
public LoginModel();
//
// Summary:
// Gets or sets the password.
[AllowHtml]
[DataType(DataType.Password)]
[Display(Name = "Password")]
[Required(ErrorMessageResourceName = "Validation_RequiredField")]
[StringLength(30, ErrorMessageResourceName = "Validation_MaxLengthExceeded")]
public virtual System.String Password { get; set; }
//
// Summary:
// Gets or sets a value indicating whether to remember the user to login him automatically
// on the next visit.
[Display(Name = "Login_RememberMe")]
public virtual System.Boolean RememberMe { get; set; }
//
// Summary:
// Gets or sets the username.
[DataType(DataType.EmailAddress, ErrorMessageResourceName = "Validation_InvalidField")]
[Display(Name = "EmailAddress")]
[Required(ErrorMessageResourceName = "Validation_RequiredField")]
[StringLength(80, ErrorMessageResourceName = "Validation_MaxLengthExceeded")]
[TrimAttribute(new[] { })]
public virtual System.String UserName { get; set; }
}
and this is the view with ajax call:
#{
Layout = LayoutPaths.General;
}
#model Sana.Commerce.DomainModel.Account.V_LoginModel_BalieUser
<h2>Index</h2>
#Html.Label("Enter Your name")
#Html.TextBox("PassId")
<div class="semicolumn">
<div class="form-holder">
#using (Html.BeginForm(htmlAttributes: new { #class = "form" }))
{
#Html.AntiForgeryToken()
<table>
<tr>
<th>
<div id="balieCode">
#Html.DisplayNameFor(modelItem => modelItem.BalieCode)
</div>
</th>
<th></th>
</tr>
<tr>
<td>
#Html.TextBoxFor(modelItem => modelItem.BalieCode)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(modelItem => modelItem.UserName)
</th>
<th></th>
</tr>
<tr>
<td>
#Html.TextBoxFor(modelItem => modelItem.UserName)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(modelItem => modelItem.Password)
</th>
<th></th>
</tr>
<tr>
<td>
#Html.TextBoxFor(modelItem => modelItem.Password)
</td>
</tr>
</table>
<div class="form-row">
<h4></h4>
<input type="submit" value="Login" />
</div>
}
</div>
<div>
</div>
</div>
#section Scripts{
#*<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery-ui.min.js"></script>*#
<script>
$(document).ready(function () {
$("#balieCode").change(function () {
$.ajax({
type: "Post",
url: '#Url.Action("GetLogindetails", "profile")',
data: { id: $("").val() },
dataType: "json",
success: function (data) {
$("#UserName").val(data[0]);
$("#Password").val(data[1]);
}
});
})
});
</script>
}

Mvc HttpPostedFileBase returns null

lately i was trying to handle HttpPostedFileBase returns null issue, but i cannot really figure it out why my input file returns null although i've researched all the similiar questions to get to know about the problem in the site.My sutiation is i need to have four input file because i need four different documents other than each other.
here is part of the view:
#using (Html.BeginForm("Create", "MyController", FormMethod.Post, new { enctype ="multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div style="padding-left: 32px;">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Id)
<table>
<tbody>
<tr>
<td style="width: 132px;"><div><b>...</b></div></td>
<td style="width:250px;">
<input type="file" name="upload1" id="upload1" class="formin" />
<input type="hidden" name="UploadType1" id="UploadType1" value="#Request.QueryString["UploadType"]" />
</td>
</tr>
<tr>
<td style="width: 132px;"><div><b>...</b></div></td>
<td style="width:250px;">
<input type="file" name="upload2" id="upload2" class="formin" />
<input type="hidden" name="UploadType2" id="UploadType2" value="#Request.QueryString["UploadType"]" />
</td>
</tr>
<tr>
<td style="width: 132px;"><div><b>...</b></div></td>
<td style="width:250px;">
<input type="file" name="upload3" id="upload3" class="formin" />
<input type="hidden" name="UploadType3" id="UploadType3" value="#Request.QueryString["UploadType"]" />
</td>
</tr>
<tr>
<td style="width: 132px;"><div><b>...</b></div></td>
<td style="width:250px;">
<input type="file" name="upload4" id="upload4" class="formin" />
<input type="hidden" name="UploadType4" id="UploadType4" value="#Request.QueryString["UploadType"]" />
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td style="width:220px;"><div><b></b></div></td>
<td> <input type="submit" name="submit" value="GÖNDER" class="formbutton" style="font-size: 14px;background:maroon;color:white;"></td>
</tr>
</tbody>
</table>
here is my controller:
[HttpPost]
public ActionResult Create(HttpPostedFileBase upload1, HttpPostedFileBase upload2, HttpPostedFileBase upload3, HttpPostedFileBase upload4, string UploadType1, string UploadType2, string UploadType3, string UploadType4)
{
List<Ek> eks = new List<Ek>();
if (upload1!=null && upload1.ContentLength > 0)
{
var upload1Name= Path.GetFileName(upload1Name.FileName);
var path1 = Path.Combine(Server.MapPath("~/Documents/.../upload1"), PhotoName);
upload1.SaveAs(path1);
Ek e1 = new Ek {
UploadType = GetTypeEnum(UploadType1),
UploadPath = "/Documents/.../.../" + upload1Name
};
eks.Add(e1);
}
if (upload2!= null && upload2.ContentLength > 0)
{
var upload2Name = Path.GetFileName(upload2.FileName);
var path2 = Path.Combine(Server.MapPath("~/Documents/.../..."), upload2Name);
upload2.SaveAs(path2);
Ek e2 = new Ek
{
UploadType = GetTypeEnum(UploadType1),
UploadPath = "/Documents/.../.../" + upload2Name
};
eks.Add(e2);
}
if (upload3!= null && upload3.ContentLength > 0)
{
var upload3Name = Path.GetFileName(upload3.FileName);
var path3 = Path.Combine(Server.MapPath("~/Documents/.../..."), upload3Name );
upload3.SaveAs(path3);
Ek e3 = new Ek
{
UploadType = GetTypeEnum(UploadType1),
UploadPath = "/Documents/.../" + upload3Name
};
eks.Add(e3);
}
if (upload4!= null && upload4.ContentLength > 0)
{
var upload4Name = Path.GetFileName(upload4.FileName);
var path4 = Path.Combine(Server.MapPath("~/Documents/.../"), upload4Name);
languagepoint.SaveAs(path4);
Ek e4 = new Ek
{
UploadType = GetTypeEnum(UploadType1),
UploadPath = "/Documents/.../" + upload4Name
};
eks.Add(e4);
}
//some stuff here
return RedirectToAction("Success");
}
return View(myview);
}
private UploadType GetTypeEnum(string UploadType1)
{
Models.UploadType uType= UploadType.MyType;
switch (UploadType1)
{
case "MyType":
uType = UploadType.MyType;
break;
case "MyType1":
uType = UploadType.MyType1;
break;
case "MyType2":
uType = UploadType.MyType2;
break;
case "MyType3":
uType = UploadType.MyType3;
break;
default:
break;
}
return uType;
}
and finally here is my modal:
public partial class MyMainClass
{
public int Id { get; set; }
public virtual IList<Ek> Ek { get; set; }
}
public partial class Ek
{
public int ID { get; set; }
public UploadType UploadType { get; set; }
public string UploadPath { get; set; }
}
public enum UploadType
{
MyType= 0,
MyType1= 1,
MyType2= 2,
MyType3= 3
}
Thank you for all the answers.
Just Correct Your HttpPost Controller as :
[HttpPost]
public ActionResult Create(IEnumerable<HttpPostedFileBase> files)
{
if (files.Count() > 0) // display no of files uploaded
if (files.Any()) // display true
if (files.First() == null) // display "first null"
return View();
}
Because you are uploading more than one file from view so you have to use IEnumerable of HttpPostedFileBase and write HttpPost attribute on Create action because it is accepting your POST Request.

error to get value from controller

i try to create new room, but roomTypeID always return 1, whats wrong with my code?
i can make a new room type, but i cant insert room facility in my database, because RoomType ID always return 1
this my code..
my controller
public ActionResult NewRoom()
{
ViewBag.hotel = _hotelService.GetByID(_HotelID).HotelName;
List<ShowEditRoomViewModel> showEditRoomViewModel = _roomTypeService.showNewRooms();
return View(showEditRoomViewModel.FirstOrDefault());
}
[HttpPost]
public ActionResult NewRoom(FormCollection typeRoom)
{
_roomTypeService.NewRoom(_HotelID, typeRoom["RoomTypeName"], typeRoom["RoomTypeDescription"]);
List<string> IDs = typeRoom["FacilityIDs"].Split(',').ToList();
List<int> FacilityIDs = new List<int>();
foreach (string ID in IDs)
{
FacilityIDs.Add(Convert.ToInt32(ID));
}
_roomTypeService.UpdateFacilityInRooms(FacilityIDs, Convert.ToInt32(typeRoom["RoomTypeID"]));
return NewRoom();
}
my service
public void UpdateFacilityInRooms(List<int> FacilityIDs, int RoomTypeID)
{
List<HotelRoomFacility> hotelRoomFacilities = _HotelRoomFacilityRopository.AsQueryable().Where(f => f.RoomTypeID == RoomTypeID).ToList();
foreach (int newRoomFacility in FacilityIDs)
{
if (hotelRoomFacilities.Where(h => h.RoomFacilityID == newRoomFacility).Count() == 0)
{
HotelRoomFacility facility = new HotelRoomFacility
{
RoomFacilityID = newRoomFacility,
RoomTypeID = RoomTypeID
};
_HotelRoomFacilityRopository.Add(facility);
}
}
_HotelRoomFacilityRopository.CommitChanges();
}
my view model
public class ShowEditRoomViewModel
{
public int RoomTypeID { get; set; }
public string RoomTypeName { get; set; }
public string RoomTypeDescription { get; set; }
public List<FaciliyInRoom> facilityinRoom { get; set; }
}
my view
#model XNet.Repository.Model.ShowEditRoomViewModel
#{
ViewBag.Title = "NewRoom";
}
<h2>New Room</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Isikan Data</legend>
<div>
#Html.Label("Hotel Name")
</div>
<div>
#ViewBag.hotel
</div>
<br />
<div>
#Html.HiddenFor(model => model.RoomTypeID)
</div>
<br />
<div>
#Html.Label("Room Type Name")
</div>
<div>
#Html.EditorFor(model => model.RoomTypeName)
#Html.ValidationMessageFor(model => model.RoomTypeName)
</div>
<br />
<div>
#Html.Label("Room Type Description")
</div>
<div>
#Html.TextAreaFor(model => model.RoomTypeDescription)
#Html.ValidationMessageFor(model => model.RoomTypeDescription)
</div>
<br />
<table>
<thead>
<tr>
<th>Facility Name</th>
<th> is available</th>
</tr>
</thead>
<tbody>
#foreach (var facility in Model.facilitiesInRoom)
{
<tr>
<td>
#(facility.RoomFacilityName)
</td>
<td style="text-align:center;">
<input type="checkbox" #(facility.RoomFacilityAvailable ? " checked=checked" : null) name="FacilityIDs" value="#facility.RoomFacilityID" />
</td>
</tr>
}
</tbody>
</table>
<br />
<p>
<input type="submit" value="Save" />
<input style="width:100px;" type="button" title="EditHotelDetail" value="Back to Detail" onclick="location.href='#Url.Action("Room", "Hotel") '" />
</p>
</fieldset>
}
My method
public List<ShowEditRoomViewModel> showNewRooms()
{
List<RoomType> roomTypes = (from d in _RoomTypeRepository.All()
select d).ToList();
List<ShowEditRoomViewModel> showEditRoomViewModel = new List<ShowEditRoomViewModel>();
foreach (RoomType roomType in roomTypes)
{
showEditRoomViewModel.Add(new ShowEditRoomViewModel
{
RoomTypeID = roomType.RoomTypeID,
facilitiesInRoom = LoadFacilityInRoom()
});
}
return showEditRoomViewModel;
}
can someone tell me, where is my mistake??
thanks
When you are inserting RoomtypeId in Database, you are using ExecuteNonQuery() method, It will always return 1 whenever you insert a new record in it,
If you are using stored procedure for inserting,you can use
select Scope_identity()
after insertion.

Resources