Passing ViewModel List Data to controller - asp.net-mvc

I have a ViewModel as such:
public class AddNewsModel
{
public List<CategoriesModel> Category { get; set; }
public NewsModel NewsModel { get; set; }
}
where Category contains:
public class CategoriesModel
{
public string Name { get; set; }
public int ID { get; set; }
}
and NewsModel contains:
public class NewsModel
{
public int ID { get; set; }
public string Category { get; set; }
public String Headline { get; set; }
public string Source { get; set; }
public DateTime Publish_Date { get; set; }
public string Text { get; set; }
public string Summary { get; set; }
public string TimeAgo { get; set; }
public string ImageURL { get; set; }
public string CategoryID { get; set; }
}
I have a View where I take form input for News using NewsModel, but I want to display possible categories as a dropdown list or select Tag from the CategoriesModel.
This is My View:
<h2>Add a News Article</h2>
#if (TempData["Success"] != null)
{
<p class="alert alert-success" id="successMessage">#TempData["Success"]</p>
}
#using (Html.BeginForm("AddNews", "Admin", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal" id="addNews">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("News ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-1">
#Html.EditorFor(model => model.NewsModel.ID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Category, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.Category, new SelectList(Model.Category), "Select Category")
#*<div class="col-md-2">
<select form="addNews" id="NewsModel_Category" name="NewsModel.Category">
#foreach (var item in Model.Category)
{
<option value="#item.Name">#item.Name</option>
}
</select>
</div>*#
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Headline, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Headline, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Headline, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Source, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Source, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Source, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Publish Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.NewsModel.Publish_Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Publish_Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Text, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Text, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Summary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Summary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Summary, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.ImageURL, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.ImageURL, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ImageURL, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
This line of code:
#Html.DropDownListFor(model => model.Category, new SelectList(Model.Category), "Select Category")
gets all the categories, but only displays them as the model I have imported int the view, viz. "MVCApplication.Models.AddNewsModel", instead of a category like "World" or "Tech"
This code that I have commented, returns null when i try to get the data in my HTTPPost controller action using formcollection. I have tried using the ID that i have provided as: string x= formCollection["category"];
<div class="col-md-2">
<select form="addNews" id="category" name="category">
#foreach (var item in Model.Category)
{
<option value="#item.Name">#item.Name</option>
}
</select>
</div>
How can I show the categories in my View, as well as get the value in the controller?
Any help would be appreciated.
Edit:
I am populating The Categories list in my controller action as:
public ActionResult AddNews()
{
AddNewsModel AddNewsModel = new AddNewsModel();
AddNewsModel.Categories = new NewsArticles().GetCategories();
return View(AddNewsModel);
}
Changing my model to an Ienumerable instead of list causes errors in my controller I cannot seem to solve.

your model should be like this:
public class AddNewsModel
{
public IEnumerable<SelectListItem> CategorySelectList { get; set; }
public int CategoryId {get; set;}
public NewsModel NewsModel { get; set; }
}
and in the view :
#Html.DropDownListFor(model => model.CategoryId, Model.CategorySelectList, "Select Category")
for more details -> link

You should have both Cateogory and List with all categories in the model
public class AddNewsModel
{
public int Category { get; set; }
public IEnumerable<SelectListItem> Categories { get; set;}
public NewsModel NewsModel { get; set; }
}
View
update your dropdownlist with list.
<h2>Add a News Article</h2>
#if (TempData["Success"] != null)
{
<p class="alert alert-success" id="successMessage">#TempData["Success"]</p>
}
#using (Html.BeginForm("AddNews", "Admin", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal" id="addNews">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("News ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-1">
#Html.EditorFor(model => model.NewsModel.ID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Category, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.Category, Model.Categories, "Select Category")
#*<div class="col-md-2">
<select form="addNews" id="NewsModel_Category" name="NewsModel.Category">
#foreach (var item in Model.Category)
{
<option value="#item.Name">#item.Name</option>
}
</select>
</div>*#
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Headline, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Headline, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Headline, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Source, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Source, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Source, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Publish Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.NewsModel.Publish_Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Publish_Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Text, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Text, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Summary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Summary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Summary, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.ImageURL, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.ImageURL, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ImageURL, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}

Related

MVC- need help for creating "Edit" View

need help about creating Edit view. I made create view and I need to be able to edit my entry sometimes. I used entity framework for connect with sql.
```
public ActionResult Create()
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CountryStateContactViewModel csvm)
{
if (!ModelState.IsValid)
{
return View(csvm);
}
Contact model = new Contact() { CountryId = csvm.CountryId, StateId = csvm.StateId, ContactId = csvm.ContactId, ImeOsobe = csvm.ImeOsobe, PrezimeOsobe = csvm.PrezimeOsobe, Komentar = csvm.Komentar, Email = csvm.Email, Aktivan = csvm.Aktivan, kcbr = csvm.kcbr, KucniBroj = csvm.KucniBroj, NazivUlice = csvm.NazivUlice, NazivNaselja = csvm.NazivNaselja, PostanskiBroj = csvm.PostanskiBroj, KontaktBroj = csvm.KontaktBroj };
db.Contacts.Add(model);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
This is Create View where I am adding new Contact from CountryStateContactViewModel (All three tables in one VIEW with 2 connected dropdown lists )
#model AkvizicijeApp_4_2.Models.CountryStateContactViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CountryStateContactViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select
Country--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContactId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContactId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContactId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PostanskiBroj, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PostanskiBroj, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PostanskiBroj, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NazivNaselja, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NazivNaselja, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NazivNaselja, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NazivUlice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NazivUlice, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NazivUlice, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.KucniBroj, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.KucniBroj, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.KucniBroj, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.kcbr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.kcbr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.kcbr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Aktivan, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Aktivan)
#Html.ValidationMessageFor(model => model.Aktivan, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImeOsobe, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ImeOsobe, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ImeOsobe, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PrezimeOsobe, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PrezimeOsobe, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PrezimeOsobe, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.KontaktBroj, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.KontaktBroj, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.KontaktBroj, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Komentar, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Komentar, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Komentar, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "
</option>")
});
});
})
});
</script>
And finally CountryStateContactViewModel, Where is id-s from first 2 tables(dropdowns) and all fields from third table.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AkvizicijeApp_4_2.Models
{
public class CountryStateContactViewModel
{
public int CountryId { get; set; }
public int StateId { get; set; }
public int ContactId { get; set; }
public int PostanskiBroj { get; set; }
public string NazivNaselja { get; set; }
public string NazivUlice { get; set; }
public string KucniBroj { get; set; }
public string kcbr { get; set; }
public bool Aktivan { get; set; }
public string ImeOsobe { get; set; }
public string PrezimeOsobe { get; set; }
public string KontaktBroj { get; set; }
public string Email { get; set; }
public string Komentar { get; set; }
}
}
Pls help me from that code (from Create View) to make Edit View (Where I can change entries
)
Thanks alot. ;)
Edit view is almost the same... the only missing property is Id:
public class EditStateContactViewModel : CountryStateContactViewModel
{
public int Id {get;set;}
}
public ActionResult Edit(int Id)
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
ViewBag.Id = Id;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EditStateContactViewModel csvm)
{
if (!ModelState.IsValid)
return View(csvm);
var item = db.Contacts.First(x=>x.Id = csvm.Id);
item.CountryId = csvm.CountryId;
item.StateId = csvm.StateId;
item.ImeOsobe = csvm.ImeOsobe;
item.PrezimeOsobe= csvm.PrezimeOsobe;
item.Komentar = csvm.Komentar ;
item.Email = csvm.Email;
item.Aktivan = csvm.Aktivan ;
item.kcbr = csvm.kcbr;
item.KucniBroj = csvm.KucniBroj;
item.NazivUlice = csvm.NazivUlice ;
item.NazivNaselja = csvm.NazivNaselja ;
item.PostanskiBroj = csvm.PostanskiBroj ;
item.KontaktBroj = csvm.KontaktBroj ;
db.Contacts.Update(item);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
And View:
#model AkvizicijeApp_4_2.Models.EditStateContactViewModel
#using (Html.BeginForm())
{
#Html.HiddenFor(x=>x.Id)
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Edit CountryStateContactViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select
Country--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
#section Scripts
{
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "
</option>")
});
});
})
});
</script>

Why when Check if the user already exists in ASP.NET MVC database first not working?

I checked more than one post in this site and tried more than one solution but still I cannot check the user exist or not when register new user , I tried the following code :
[HttpPost]
public ActionResult register(Registration reg)
{
if (ModelState.IsValid)
{
var userexist = db.Registration.Any(x => x.username == reg.username);
if (userexist)
{
ModelState.AddModelError("username", "User with this name already exists");
return View(reg);
}
else
{
db.Registration.Add(reg);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View();
}
this is registration model :
namespace registration.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Registration
{
public int Userid { get; set; }
[Required]
[Display(Name ="ID or Iqama No ")]
public string username { get; set; }
[Required]
[Display(Name = "Medical Record Number ")]
public int PatientNo { get; set; }
[Required]
[Display(Name = "Mobile ")]
public string Mobile { get; set; }
[Display(Name = "Email Address ")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
this is the view code and submit button there create button:
#model registration.Models.Registration
#{
ViewBag.Title = "Register New User";
}
<h2>register</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Registration Window</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.username, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" >
#Html.EditorFor(model => model.username, new { htmlAttributes = new { #type = "number", #min = "0", #value = "0", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PatientNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PatientNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PatientNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Login")
</div>
what is the missing in my code why its not working when click enter or tab or by mouse click its not checking ?
Your code correct and no errors ,
You said
"when click enter or tab or by mouse click its not checking ?"
This code will work when you click the button Submit or Create .
The code will validate the username exist or not and not when you navigate grom the username field.
Try this:
#using (Html.BeginForm("register", "YourControllerName", FormMethod.Post, new { #id = "LoginForm", #autocomplete = "off"}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Registration Window</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.username, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" >
#Html.EditorFor(model => model.username, new { htmlAttributes = new { #type = "number", #min = "0", #value = "0", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PatientNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PatientNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PatientNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult register(Registration reg)
{
if (ModelState.IsValid)
{
var userexist = db.Registration.Any(x => x.username == reg.username);
if (userexist)
{
ModelState.AddModelError("username", "User with this name already exists");
return View(reg);
}
else
{
db.Registration.Add(reg);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View();
}

POST form in MVC - No Values being written to DB

I have a model that I'm trying to edit with a form:
public class Basiclife
{
[Key]
public int Id { get; set; }
public int? ResponseId { get; set; }
public string Plantype { get; set; }
public int Enrolledftes { get; set; }
public decimal Pctemployer { get; set; }
public decimal Fixedbenamt { get; set; }
public decimal Salarymult { get; set; }
public decimal Bencap { get; set; }
}
And a view wrapper to edit it (with the editor in a separate partial view):
<h2>CreateBasicLifeResponse</h2>
<div id="planList">
#using (Html.BeginForm("CreateBasicLifeResponse", "Surveys"))
{
<div id="editorRows">
#foreach (var item in Model.basiclives)
{
#Html.Partial("_BasicLifeResponse", item)
}
</div>
#Html.ActionLink("Add", "BasicLifeResponse", null, new { id = "addItem", #class = "button" });
<input type="submit" value="submit" />
}
</div>
The wrapper's model is:
public class ResponseBasicLife
{
public Response response { get; set; }
public List<Basiclife> basiclives { get; set; }
}
Here's the partial view:
#using CustomSurveyTool.Models
#model Basiclife
<div class="editorRow">
#using (Html.BeginCollectionItem("basiclives"))
{
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Plantype, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Plantype, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Plantype, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Enrolledftes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Enrolledftes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Enrolledftes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Pctemployer, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Pctemployer, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Pctemployer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Fixedbenamt, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Fixedbenamt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Fixedbenamt, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Salarymult, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Salarymult, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Salarymult, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Bencap, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Bencap, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Bencap, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
X
</div>
</div>
}
</div>
Here's my controller action where I'm getting the proper responseId and assigning it to the form values:
public ActionResult CreateBasicLifeResponse(ResponseBasicLife model)
{
for (var i = 1; i < model.basiclives.Count; i++)
{
string currentUserId = User.Identity.GetUserId();
Response targetresponse = db.response.FirstOrDefault(x => x.Userid == currentUserId);
int responseid = targetresponse.Id;
model.basiclives[i].ResponseId = responseid;
db.basiclife.Add(model.basiclives[i]);
db.SaveChanges();
}
ResponseBasicLife basicliferesponse = new ResponseBasicLife
{
basiclives = new List<Basiclife>
{
new Basiclife { }
}
};
return View(basicliferesponse);
}
The only thing that's being written to the database is the ResponseID. How do I get the rest of the values to write to it?
This is a unique case where EditorFor could help. Essentially an object will have its editor template which is kind of like a partial view but specific to editing forms.
Secondly, the being form you are specifying is expecting the model of the view that you specified - in your case the viewWrapper. If for instance you specified a List<BasicLife>, then that is what the postBack shall be expecting, and not the BasicLife object. Below is how your postback would look like.
[HttpPost]
public ActionResult CreateBasicLifeResponse(List<BasicLife> model){
//your code goes here
}
From your view though, it looks clear that Model contains more than just a list. That is what shall be expected from the callback.

Cannot save values from form to database

I am trying to write my first ASP.NET MVC application with Entity Framework (code first).
I am trying to insert data from form to specific table in database but it does not work. When I press "Submit" button, page is refreshing but table still has not any value. There is no error on page or in console.
Could you please take a look on code and help me ?
Below is my code:
View:
#model VeterinaryApp.Models.Clients
#{
ViewBag.Title = "AddClient";
Layout = "~/Views/SharedViews/_MainLayout.cshtml";
}
<h2>AddClient</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Clients</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Surname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Surname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Surname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Controller:
public class AddClientController : Controller
{
// GET: AddClient
public ActionResult AddClient()
{
return View();
}
//POST
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ClientsId, Name, Surname, Email, Phone")] Clients clients)
{
if (ModelState.IsValid)
{
using (StoreContext db = new StoreContext()) //DbContext
{
db.Clients.Add(clients);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(clients);
}
}
Model
public class Clients
{
public int ClientsId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public int Phone { get; set; }
public virtual ICollection<BookVisit> BookedVisits { get; set; }
public virtual ICollection<Animals> OwnedAnimals { get; set; }
}

Don't fire a required validator for

I have the following model:
public class Model1
{
[Required(ErrorMessage="E1")]
public string Name { get; set; }
[Required(ErrorMessage="E2")]
[RegularExpression(".+\\#.+\\..+")]
public string Email { get; set; }
[Required(ErrorMessage="E3")]
public bool WillAttend { get; set; }
}
controller action:
public ActionResult Model1()
{
Model1 m = new Model1();
return View(m);
}
and view:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Model1</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.WillAttend, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.WillAttend)
#Html.ValidationMessageFor(model => model.WillAttend, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
problem is required validator for WillAttend property does not work. Even in action method, ModelState.IsValid is true. Why and how to do WillAttend is required ?
At the moment, your required-attribute just checks whether a value was specified. Since a boolean is either true or false, the validation will never fail.
You can, mark the boolean as nullable:
public bool? WillAttend { get; set; }
or you can try to make a custom validator if you are trying to force them to check the box, such as in this link.

Resources