How do I create a new db entry and populate the foreign key based on autocomplete selection of that foreign key object? - asp.net-mvc

I have a ASP.NET MVC application i am developing, and have a repair model that includes a foreign key to a serial number model. In my view i have a typeahead jquery doing a autocomplete search through database to allow the user to select a serial number already in the database. I then have fields to fill out new information that will populate the repair table. I cannot seem to get the selected SerialNumber.Id to populate in the Repair.SerialNumber_Id from the selected serial number.
my view:
#model EntityTestApp.Models.Repair
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Repair</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.RepairDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RepairDate, new {htmlAttributes = new { #class = "form-control", #Value = DateTime.Now.ToShortDateString() } })
#Html.ValidationMessageFor(model => model.RepairDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SerialNumber, htmlAttributes: new { #class = "control-label col-md-2"})
<div class="col-md-10">
<input id="serialNumberTextBox" type="text" value="" class="form-control" />
#Html.ValidationMessageFor(model => model.SerialNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CustomerComplaint, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.CustomerComplaint, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CustomerComplaint, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IssueFound, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.IssueFound, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.IssueFound, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RepairActionTaken, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.RepairActionTaken, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RepairActionTaken, "", 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>
#section scripts{
<script>
$(document).ready(function () {
var SerialNumbers = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Number'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/serialnumbers?query=%QUERY',
wildcard: '%QUERY'
}
});
$('#serialNumberTextBox').typeahead({
highlight: true
}, {
name: 'SerialNumbers',
display: 'Number',
source: SerialNumbers
}).on("typeahead:select", function (e, SerialNumber) {
//alert(serialNumberTextBox.value)
});
});
</script>
}
my Controller action to create a new repair entry:
// GET: Repairs/Create
public ActionResult Create()
{
return View();
}
// POST: Repairs/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Repair repair)
{
if (ModelState.IsValid)
{
db.Repairs.Add(repair);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(repair);
}
And my repair model:
public class Repair
{
public int Id { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime RepairDate { get; set; }
public SerialNumber SerialNumber { get; set; }
public string CustomerComplaint { get; set; }
public string IssueFound { get; set; }
public string RepairActionTaken { get; set; }
}

Ok, several hair pulling nights later i figured it out. I had to add a hidden field to hold the value for the foreign key and assign that value based on the 'typeahead' javascript autocomplete selection with "document.getElementById('').
Works like a charm. Thanks for the help!
-Chris

Related

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

Why DefaultModelBinder doesn't bind route value ID from URL

ASP.NET MVC
In short:
I have a get action and a post action
when I type in browser localhost:port/Employee/Edit/1 I call get action, so in URL I have this whole url string. When I press submit button, in post action defaultmodelbinder doesnt bind id from URL!!!! I HAVE TO ADD HIDDEN FIELD for id. But why? I also have delete action (post), that gets id too, and I dont need to add hidden field for id. why?
More specifically:
I have the model:
public class EmployeeViewModel
{
public Int32 EmployeeId { get; set; }
public String Name { get; set; }
public String Phone { get; set; }
public String Email { get; set; }
public String Other { get; set; }
}
And 2 actions
public ActionResult Edit(int id)
{
try
{
EmployeeViewModel model;
using (var dbSession = NHibernateHelper.OpenSession())
{
var employee = dbSession.Query<Employee>().First(e => e.EmployeeId == id && e.ExpireDate==null);
model = new EmployeeViewModel(employee);
}
return View(model);
}
catch
{
return View("Error");
}
}
[HttpPost]
public ActionResult Edit(EmployeeViewModel model)
{
try
{
using (var dbSession=NHibernateHelper.OpenSession())
using (var transaction=dbSession.BeginTransaction())
{
var employee = model.ToEmployee();
dbSession.Merge(employee);
transaction.Commit();
}
return RedirectToAction("Index");
}
catch
{
return View("Error");
}
}
And 1 View (HERE I HAVE TO WRITE THIS LINE #Html.HiddenFor(model => model.EmployeeId) )
#using (Html.BeginForm()){
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.HiddenFor(model => model.EmployeeId)
#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.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">
#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.Other, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Other, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Other, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Сохранить" class="btn btn-default" />
</div>
</div>
</div>}
Because the parameter in the method is named id and the property in
your model is named EmployeeId They are not the same. And if you
change the model property to Id it will be bound
Thanks, Stephen Muecke

ViewBag does not work

I'm trying to create an MVC site and I have some trubble with the ViewBag.
It's like it can't contain elements.
I'm using MVC 4.
This is my function in the controller:
public ActionResult Create()
{
ViewBag.DiscID = new SelectList(entities.Disc, "ID", "ID");
ViewBag.StarID = new SelectList(entities.Star, "ID", "Name");
ViewBag.Num = 7;
return View();
}
This is my Create view:
#model Movies.Models.StarAndRole
#{
ViewBag.Title = "Create";
int num;
int.TryParse(ViewBag.Num, out num);
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>StarAndRole</h4>
<h3>num is = #num</h3>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.StarID, "Star", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("StarID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StarID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DiscID, "Disc Num", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("DiscID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.DiscID, "", 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>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
It appears to me that everything I put in the ViewBag is NULL.
What am i doing wrong?
Thank you in advance!
Int.TryParse method accepts a string (representation of the int value). But you are passing a dynamic type to the method. It should give you an error about that.
If you know you are setting an Int value from your action method, in your view, you can simply read it like
int num = ViewBag.Num;
A better solution is to add the data you want to pass to the view to your view model.
public class YourCreateVm
{
public string Description { set;get;}
public int Num { set;get;}
public List<SelectListItem> Disks { set;get;}
public int SelectedDiskId { set;get;}
}
and in your GET view
public ActionResult Create()
{
var vm = new YourCreateVm { Num = 7 };
vm.Disks = entities.Disc.Select(s=> new SelectListItem
{ Value=s.ID.ToString(), Text =s.Name}).ToList();
return View(vm);
}
and in your view
#model YourCreateVm
#using(Html.BeginForm())
{
<p>My num is : #Model.Num <p>
#Html.TextBoxFor(s=>s.Description)
#Html.DropDownListFor(s=>s.SelectedDiskId, Model.Disks)
<input type="submit" />
}

The current request for action ... on controller type ... is ambiguous between the following action methods

When I run the application on browser with ~/Person/New the result is
The current request for action 'New' on controller type 'PersonController' is ambiguous between the following action method System.Web.Mvc.ActionResult New() on type PersonMVC.Controllers.PersonController System.Web.Mvc.ActionResult New(PersonMVC.Models.Person) on type PersonMVC.Controllers.PersonController
Model
namespace PersonMVC.Models
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
[Required]
[DisplayName("Social Sequrity Number")]
[MinLength(11, ErrorMessage ="Social Security Number Must be 11 digit.")]
[MaxLength(11, ErrorMessage ="")]
public string SocialSecurityNumber { get; set; }
[DisplayFormat(DataFormatString ="{0:dd.MM.yyyy}")]
public DateTime BirthDay { get; set; }
}
}
-View
#model PersonMVC.Models.Person
#{
ViewBag.Title = "New";
}
<h2>New</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Person</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.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SocialSecurityNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SocialSecurityNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SocialSecurityNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BirthDay, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BirthDay, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BirthDay, "", 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>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Controller
namespace PersonMVC.Controllers
{
public class PersonController : Controller
{
public ActionResult New()
{
return View();
}
[HttpPost]
public ActionResult New(Person newPerson)
{
bool isTrue = ModelState.IsValid;
return View();
}
}
}
you need to decorate the method with appropriate http verb. Otherwise it will be considered as HttpPost usually.
i think adding [HttpPost] to the controller method would solve the problem

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