Getting message “Store update, insert, or delete statement affected an unexpected number of rows (0)” ? - asp.net-mvc

Another big problem, here.
I have the model:
public class Lead
{
[System.ComponentModel.DataAnnotations.Column("le_codlead")]
public int LeadID {get; set; }
[System.ComponentModel.DataAnnotations.Column("le_descr1")]
[Required(ErrorMessage="Inserire Nome del Lead")]
[Display(Name="Nominativo Lead")]
public string Name1 {get; set;}
[System.ComponentModel.DataAnnotations.Column("le_descr2")]
[Display(Name = "Nominativo secondario")]
public string Name2 { get; set; }
...
...
...
}
Controller (for the Create Method):
[HttpPost]
public ActionResult Create(Lead lead)
{
if (ModelState.IsValid)
{
db.Leads.Add(lead);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(lead);
}
and this is the View:
#model CRMArcadia.Models.Lead
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true, "ATTENZIONE! Compilare tutti i campi obbligatori")
<fieldset>
<legend>Lead</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name1)
#Html.ValidationMessageFor(model => model.Name1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Name2)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name2)
#Html.ValidationMessageFor(model => model.Name2)
</div>
...
...
...
<p>
<input type="submit" value="Create" />
</p>
</fieldset> }
But when I try to insert a new Lead it throws the exception as in the Post Title: Entity Framework: “Store update, insert, or delete statement affected an unexpected number of rows (0).” I read on the web it is caused by the ID key (LeadID, in this case) not updating: they suggest to insert an hiddenfor attribute in the view for the ID key, and so I did:
#Html.HiddenFor(model => model.LeadID)
But with this one at the pressure of the Create button nothing happens.
Does someone has a solution (or a workaround ;) ) at this problem, please?
Thanks.

Do you have some extra layer to communicate with EF ? what is your entity context?
For Update scenario:
If you are using same action for Create/Edit then just place your #Html.HiddenFor(model => model.LeadID) - hidden field between blocks #using (Html.BeginForm()) { .... </fieldset> }.
If it does not help, look at this article MSDN - Working with Objects

Related

How to customize ASP.net MVC jquery unobtrusive validation message display

by default MVC use jquery unobtrusive validation lib to show validation message at client side. suppose i have small form with two textbox for first name and last name. when click submit button then client side validation will fire and display all validation message at once. but i want to display validation message one by one. now tell me where to customize the code and what code need to add or modify in js to make it possible.
here is my small sample code
namespace MVC_myfirst_Mvcapplication.Models
{
public class Person
{
public int ID { get; set; }
[Required]
[StringLength(30)]
public string First { get; set; }
[Required]
[StringLength(30)]
public string Last { get; set; }
public DateTime Birthdate { get; set; }
}
public class PersonContext : DbContext
{
public DbSet<Person> People { get; set; }
}
}
Controller : PersonController.cs
public class PersonController : Controller
{
PersonContext db = new PersonContext();
//
// GET: /Person/
public ActionResult Index()
{
var People = db.People.ToList();
return View(People);
}
//
// GET: /Person/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Person/Create
[HttpPost]
public ActionResult Create(Person Person)
{
db.People.Add(Person);
db.SaveChanges();
return RedirectToAction("Index");
}
}
View:
#model MVC_myfirst_Mvcapplication.Models.Person
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
<div class="editor-label">
#Html.LabelFor(model => model.First)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.First)
#Html.ValidationMessageFor(model => model.First)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Last)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Last)
#Html.ValidationMessageFor(model => model.Last)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Birthdate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Birthdate)
#Html.ValidationMessageFor(model => model.Birthdate)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
tell me which code i need to change in js to show validation message one-by-one in a specific div? thanks

MVC3 View doesn`t display empty form on validation passed

Very simple situation, here is my model:
public class Comment
{
[Required]
public string Name { get; set; }
[Required]
public string Text { get; set; }
}
Here is my controller:
public class CommentController : Controller
{
//
// GET: /Comment/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Comment/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
Comment new_comment = new Comment();
if (TryUpdateModel(new_comment))
{
return View(new Comment()); //problem is there
}
else
{
return View(new_comment);
}
}
}
And here is my standart genered strongly-typed View:
#model test.Models.Comment
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Comment</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Text)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Text)
#Html.ValidationMessageFor(model => model.Text)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Problem is: when I enter valid data, TryUpdateModel() returns true, and
return View(new Comment());
should display empty form, because new empty instance of Comment is passed, but it still displays form with values entered earlier.
Please somebody tell me why. How to make it display empty form again?
Clear the modelstate:
if (TryUpdateModel(new_comment))
{
ModelState.Clear();
return View(new Comment()); //no more problem here
}
All HTML helpers first look at the ModelState when rendering their values and only after that in the model.
Or even better and more properly use the Redirect-After-Post pattern (i.e. redirect after a successful POST):
if (TryUpdateModel(new_comment))
{
return RedirectToAction("Create");
}

MVC3 - How to add dropdown to a form (Post) populated with different entity

Hi I am working in a MVC 3 application. I have a Create Form with following code.
#model Xrm.Student
#{
ViewBag.Title = "Create Student Record";
}
#using (Html.BeginForm("Create", "Student", FormMethod.Post))
{
<div class="editor-label">
#Html.LabelFor(model => #Model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => #Model.FirstName)
#Html.ValidationMessageFor(model => #Model.FirstName)
</div>
<div>
<input id="Submit1" type="submit" value="Submit" />
</div>
}
I want to add a new drop down under Firsname field which should be populated with pubjects. Subject is different Entity. I could be very easy, but I am newbie with MVC so I just stuck here. Can anyone please suggest me the way to achieve it.
Thanks and Regards
I would define a view model:
public class MyViewModel
{
public Student Student { get; set; }
[DisplayName("Subject")]
[Required]
public string SubjectId { get; set; }
public IEnumerable<Subject> Subjects { get; set; }
}
and then have your controller populate and pass this view model to the view:
public ActionResult Create()
{
var model = new MyViewModel();
model.Student = new Student();
model.Subjects = db.Subjects;
return View(model);
}
and finally have your view strongly typed to the view model:
#model MyViewModel
#{
ViewBag.Title = "Create Student Record";
}
#using (Html.BeginForm())
{
<div class="editor-label">
#Html.LabelFor(x => x.Student.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(x => x.Student.FirstName)
#Html.ValidationMessageFor(x => x.Student.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(x => x.SubjectId)
</div>
<div class="editor-field">
#Html.DropDownListFor(
x => x.SubjectId,
new SelectList(Model.Subjects, "Id", "Name"),
"-- Subject --"
)
#Html.ValidationMessageFor(x => x.SubjectId)
</div>
<div>
<input type="submit" value="Submit" />
</div>
}
The "Id" and "Name" values I used for the SelectList must obviously be existing properties on your Subject class that you want to be used as respectively binding the id and the text of each option of the dropdown.

DateTime required in ModelState, however never set to be

I have a DateTime field in my form. For whatever reason, everytime I submit the form ModelState comes back as invalid and a message that my date time field (called PostDate) is required, even though in the view model I don't have the required attribute set.
Does anyone know why this would be happening as I'm going around in circles trying to figure it out.
Here is the view model
public class BlogViewModel
{
[Required]
public string Title { get; set; }
[Required]
public string Content { get; set; }
public bool Published { get; set; }
public DateTime PostDate { get; set; }
}
Here is the controller actions
public ActionResult Create()
{
return View();
}
//
// POST: /Admin/Blog/Create
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(BlogViewModel model)
{
if(ModelState.IsValid)
{
model.Content = HtmlSanitizer.SanitizeHtml(model.Content);
Services.BlogService.CreateBlogPost(model.Title, model.Content, User.Identity.Name);
return RedirectToAction("Index");
}
return View(model);
}
Here is the View
#using Payntbrush.Infrastructure.Mvc.Extensions
#model Payntbrush.Presentation.Demo.MVC3.Areas.Admin.Models.BlogViewModel
#Html.Resource(Html.ScriptTag("Areas/Admin/js/plugins/wysiwyg/jquery.wysiwyg.js"), ResourceType.Js)
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm((string)ViewBag.Action, "Blog", FormMethod.Post, new { Id = "BlogEditor" }))
{
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Content)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Content, new { #class = "wysiwyg blog-editor" })
#Html.ValidationMessageFor(model => model.Content)
</div>
<div class="editor-label">
Time of post (Only set this if you want to make a post appear to have been published at a different date.)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.PostDate, new{#class="datetimepicker"})
#Html.ValidationMessageFor(model => model.PostDate)
</div>
<div class="editor-label">
Published (Check to make this post live on the site)
</div>
<div class="editor-field">
#Html.CheckBoxFor(model => model.Published)
#Html.ValidationMessageFor(model => model.Published)
</div>
<p>
<input class="large awesome" type="submit" value="Create" />
#Html.ActionLink("Cancel", "Index", "Blog", null, new { #class = "large awesome cancel-button" })
</p>
}
<div>
</div>
If you leave the corresponding field empty your model will be invalid because DateTime is a value type. You should use a nullable DateTime if you want to allow empty values:
public DateTime? PostDate { get; set; }

keeping Object Data after passing it to a strongly typed view

I have a simple ASP.NET MVC 3 site, from my Controller out of the Edit Action I pass a Object (a class which is also mapped by nhibernate)
After editing and clicking save i pass it to the [HTTPPost] decoraded Method but and all properties are correct, excerpt the "id" property it hat a guid value equivalent to NULL (00000000-0000-000...).
Is there a problem using the Domain Model to strongly type my Views? May the problem be that Id has:
{get; private set;}
???
Thanks in advance.
Here The Code:
My View:
'#model fnh.DataModel.Kunde
#{
View.Title = "EditKunde";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>EditKunde</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Fields</legend>
#Html.EditorFor(model => model._id)
#Html.EditorFor(model => model._KdNr);
<div class="editor-label">
#Html.LabelFor(model => model._Name)
`enter code here` </div>
<div class="editor-field">
#Html.EditorFor(model => model._Name)
#Html.ValidationMessageFor(model => model._Name)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
'
My Controller Actions:
' public ActionResult EditKunde(Guid id)
{
return View(_kunden.GetKundeById(id));
}
[HttpPost]
public ActionResult EditKunde(Kunde kunde)
{
Ansprechpartner anp = new Ansprechpartner();
anp._Name = "JustATry";
kunde._Ansprechpartner.Add(anp);
`enter code here` _kunden.EditKunde(kunde);
return View();
}'
Are you adding the Id property to your form (maybe as a hidden field)?
It would be useful if you post the Action code (for both Edit Actions), and the View.

Resources