ASP.MVC The required anti-forgery form field errors - asp.net-mvc

I'm Beginner in MVC and Bootstrap. I Want Create Form Like This
I Want When user Click in New Button open Create View In Modal Bootstrap and when user Click in Edit Link Open Edit View in Modal Bootstrap . I Write this Code
// <![CDATA[
(function ($) {
$.bootstrapModalAjaxForm = function (options) {
var defaults = {
renderModalPartialViewUrl: null,
renderModalPartialViewData: null,
postUrl: '/',
loginUrl: '/login',
beforePostHandler: null,
completeHandler: null,
errorHandler: null
};
var options = $.extend(defaults, options);
var validateForm = function (form) {
var val = form.validate();
val.form();
return val.valid();
};
var enableBootstrapStyleValidation = function () {
$.validator.setDefaults({
highlight: function (element, errorClass, validClass) {
if (element.type === 'radio') {
this.findByName(element.name).addClass(errorClass).removeClass(validClass);
} else {
$(element).addClass(errorClass).removeClass(validClass);
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
}
$(element).trigger('highlited');
},
unhighlight: function (element, errorClass, validClass) {
if (element.type === 'radio') {
this.findByName(element.name).removeClass(errorClass).addClass(validClass);
} else {
$(element).removeClass(errorClass).addClass(validClass);
$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
}
$(element).trigger('unhighlited');
}
});
}
var enablePostbackValidation = function () {
$('form').each(function () {
$(this).find('div.form-group').each(function () {
if ($(this).find('span.field-validation-error').length > 0) {
$(this).addClass('has-error');
}
});
});
}
var processAjaxForm = function (dialog) {
$('form', dialog).submit(function (e) {
e.preventDefault();
if (!validateForm($(this))) {
return false;
}
if (options.beforePostHandler)
options.beforePostHandler();
$.ajaxSetup({ cache: false });
$.ajax({
url: options.postUrl,
type: "POST",
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#dialogDiv').modal('hide');
if (options.completeHandler)
options.completeHandler();
} else {
$('#dialogContent').html(result);
$.validator.unobtrusive.parse("#dialogContent");
enablePostbackValidation();
processAjaxForm('#dialogContent');
if (options.errorHandler)
options.errorHandler();
}
}
});
return false;
});
};
var mainContainer = "<div id='dialogDiv' class='modal fade'><div id='dialogContent'></div></div>";
enableBootstrapStyleValidation();
$.ajaxSetup({ cache: false });
$.ajax({
type: "POST",
url: options.renderModalPartialViewUrl,
data: options.renderModalPartialViewData,
//contentType: "application/json; charset=utf-8",
// headers: { __RequestVerificationToken: $("input[name=__RequestVerificationToken]").val() },
// dataType: "json",
dataType: "html",
complete: function (xhr, status) {
var data = xhr.responseText;
var data = xhr.responseText;
if (xhr.status == 403) {
window.location = options.loginUrl;
}
else if (status === 'error' || !data) {
if (options.errorHandler)
options.errorHandler();
}
else {
var dialogContainer = "#dialogDiv";
$(dialogContainer).remove();
$(mainContainer).appendTo('body');
$('#dialogContent').html(data);
$.validator.unobtrusive.parse("#dialogContent");
enablePostbackValidation();
$('#dialogDiv').modal({
backdrop: 'static',
keyboard: true
}, 'show');
processAjaxForm('#dialogContent');
}
}
});
};
})(jQuery);
// ]]>
and controller
public partial class CityController : Controller
{
private ArchiveEntities db = new ArchiveEntities();
// GET: /City/
public virtual ActionResult Index()
{
return View(db.CITIES.ToList());
}
// GET: /City/Details/5
public virtual ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CITy city = db.CITIES.Find(id);
if (city == null)
{
return HttpNotFound();
}
return View(city);
}
// GET: /City/Create
[ValidateAntiForgeryToken]
public virtual ActionResult Create()
{
return View();
}
// POST: /City/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 virtual ActionResult Create([Bind(Include = "CITY_ID,CITY_NAME,CITY_ABBR,REMARK")] CITy city)
{
if (this.ModelState.IsValid)
{
//todo: SaveChanges;
db.CITIES.Add(city);
db.SaveChanges();
return Json(new { success = true });
}
this.ModelState.AddModelError("", "Error");
return PartialView("_ModalPartialView", city);
//if (ModelState.IsValid)
//{
// db.CITIES.Add(city);
// db.SaveChanges();
// // return View(MVC.City.RenderModalPartialView());
//}
//return View();
}
// GET: /City/Edit/5
[ValidateAntiForgeryToken]
public virtual ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CITy city = db.CITIES.Find(id);
if (city == null)
{
return HttpNotFound();
}
// return View(city);
return PartialView(Views._Edit, city);
}
// POST: /City/Edit/5
// 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 virtual ActionResult Edit([Bind(Include = "CITY_ID,CITY_NAME,CITY_ABBR,REMARK")] CITy city)
{
if (ModelState.IsValid)
{
db.Entry(city).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(city);
}
// GET: /City/Delete/5
public virtual ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CITy city = db.CITIES.Find(id);
if (city == null)
{
return HttpNotFound();
}
return View(city);
}
// POST: /City/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public virtual ActionResult DeleteConfirmed(int id)
{
CITy city = db.CITIES.Find(id);
db.CITIES.Remove(city);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
[HttpGet]
public virtual ActionResult List()
{
return PartialView(Views._CityList, db.CITIES.ToList());
}
[HttpPost]
// [AjaxOnly]
// [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public virtual ActionResult List2()
{
return PartialView(Views._CityList, db.CITIES.ToList());
}
public virtual ActionResult RenderModalPartialView()
{
return PartialView(viewName: "_ModalPartialView", model: new CITy() { CITY_ABBR = "", CITY_NAME = "" });
}
[HttpPost]
//[AjaxOnly]
public virtual ActionResult Index(CITy user)
{
if (this.ModelState.IsValid)
{
//todo: SaveChanges;
return Json(new { success = true });
}
this.ModelState.AddModelError("", "Error");
return PartialView("_ModalPartialView", user);
}
}
}
and Index View
<div id="info">
#Html.Action(MVC.City.List())
</div>
#section JavaScript
{
<script type="text/javascript">
function addToken(data) {
data.__RequestVerificationToken = $("input[name=__RequestVerificationToken]").val();
return data;
}
function EditPopup(id) {
$.bootstrapModalAjaxForm({
postUrl: '#postEditUrl',
renderModalPartialViewUrl: '#renderModalPartialViewEditUrl',
renderModalPartialViewData:addToken({ id: id }),
loginUrl: '/login',
beforePostHandler: function () {
alert('beforePost');
},
completeHandler: function () {
$.ajax({
type: "POST",
url: '#loadInfoUrl',
complete: function (xhr, status) {
var data = xhr.responseText;
if (xhr.status == 403) {
window.location = "/login";
}
else if (status === 'error' || !data || data == "nok") {
alert('error');
}
else {
$("#info").html(data);
}
}
});
},
errorHandler: function () {
alert("error");
}
});
}
$(function () {
$('#btnCreate').click(function(e) {
e.preventDefault(); //مي‌خواهيم لينك به صورت معمول عمل نكند
$.bootstrapModalAjaxForm({
postUrl: '#postDataUrl',
renderModalPartialViewUrl: '#renderModalPartialViewUrl',
renderModalPartialViewData: {},
loginUrl: '/login',
beforePostHandler: function() {
alert('beforePost');
},
completeHandler: function() {
$.ajax({
type: "POST",
url: '#loadInfoUrl',
complete: function (xhr, status) {
var data = xhr.responseText;
if (xhr.status == 403) {
window.location = "/login";
}
else if (status === 'error' || !data || data == "nok") {
alert('error ajax');
}
else {
$("#info").html(data);
}
}
});
// alert('completeHandler');
},
errorHandler: function() {
alert("error");
}
});
});
});
</script>
}
and _CityList
#model IEnumerable<TestTwiter.Models.CITy>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CITY_NAME)
</th>
<th>
#Html.DisplayNameFor(model => model.CITY_ABBR)
</th>
<th>
#Html.DisplayNameFor(model => model.REMARK)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.CITY_NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.CITY_ABBR)
</td>
<td>
#Html.DisplayFor(modelItem => item.REMARK)
</td>
<td>
<span onclick="EditPopup(#item.CITY_ID)">Edit</span>|||||
<a href="JavaScript:void(0)" onclick="EditPopup(#item.CITY_ID)" >Edit</a>
#*#Html.ActionLink("Edit", "Edit", new { id=item.CITY_ID }) |*#
#Html.ActionLink("Details", "Details", new { id=item.CITY_ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.CITY_ID })
</td>
</tr>
}
</table>
and _ModalPartialView
#model TestTwiter.Models.CITy
#{
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, null, new { #class = "alert alert-warning" })
#Html.AntiForgeryToken()
<div>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title">
Title
</h4>
</div>
<div class="modal-body">
<fieldset class="form-horizontal">
<legend>User</legend>
<div class="form-group">
#Html.LabelFor(model => model.CITY_NAME, new { #class = "col col-lg-4 control-label" })
<div class="col col-lg-8 controls">
#Html.EditorFor(model => model.CITY_NAME)
#Html.ValidationMessageFor(model => model.CITY_NAME, null, new { #class = "help-block" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CITY_ABBR, new { #class = "col col-lg-4 control-label" })
<div class="col col-lg-8 controls">
#Html.EditorFor(model => model.CITY_ABBR)
#Html.ValidationMessageFor(model => model.CITY_ABBR, null, new { #class = "help-block" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.REMARK, new { #class = "col col-lg-4 control-label" })
<div class="col col-lg-8 controls">
#Html.EditorFor(model => model.REMARK)
#Html.ValidationMessageFor(model => model.REMARK, null, new { #class = "help-block" })
</div>
</div>
</fieldset>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="submit">
Send
</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">
Cancel
</button>
</div>
</div>
</div>
</div>
}
and _Edit
#model TestTwiter.Models.CITy
#using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>CITy</h4>
<hr />
#Html.ValidationSummary(true)
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.CITY_ID)
<div class="form-group">
#Html.LabelFor(model => model.CITY_NAME, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CITY_NAME)
#Html.ValidationMessageFor(model => model.CITY_NAME)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CITY_ABBR, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CITY_ABBR)
#Html.ValidationMessageFor(model => model.CITY_ABBR)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.REMARK, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.REMARK)
#Html.ValidationMessageFor(model => model.REMARK)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
when user click in New Link Modal form Work Good, but when user Click in Edit Button I get This Error
The required anti-forgery form field "__RequestVerificationToken" is not present
Please Help me. Thanks all
EDIT-01: remove [ValidateAntiForgeryToken] from ALL of GET requests
public partial class CityController : Controller
{
private ArchiveEntities db = new ArchiveEntities();
// GET: /City/
public virtual ActionResult Index()
{
return View(db.CITIES.ToList());
}
// GET: /City/Details/5
public virtual ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CITy city = db.CITIES.Find(id);
if (city == null)
{
return HttpNotFound();
}
return View(city);
}
// GET: /City/Create
//[ValidateAntiForgeryToken]
public virtual ActionResult Create()
{
return View();
}
// POST: /City/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 virtual ActionResult Create([Bind(Include = "CITY_ID,CITY_NAME,CITY_ABBR,REMARK")] CITy city)
{
if (this.ModelState.IsValid)
{
//todo: SaveChanges;
db.CITIES.Add(city);
db.SaveChanges();
return Json(new { success = true });
}
this.ModelState.AddModelError("", "Error");
return PartialView("_ModalPartialView", city);
//if (ModelState.IsValid)
//{
// db.CITIES.Add(city);
// db.SaveChanges();
// // return View(MVC.City.RenderModalPartialView());
//}
//return View();
}
// GET: /City/Edit/5
// POST: /City/Edit/5
// 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 virtual ActionResult Edit([Bind(Include = "CITY_ID,CITY_NAME,CITY_ABBR,REMARK")] CITy city)
//{
// if (ModelState.IsValid)
// {
// db.Entry(city).State = EntityState.Modified;
// db.SaveChanges();
// return RedirectToAction("Index");
// }
// return View(city);
//}
// GET: /City/Delete/5
public virtual ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CITy city = db.CITIES.Find(id);
if (city == null)
{
return HttpNotFound();
}
return View(city);
}
// POST: /City/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public virtual ActionResult DeleteConfirmed(int id)
{
CITy city = db.CITIES.Find(id);
db.CITIES.Remove(city);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
[HttpGet]
public virtual ActionResult List()
{
return PartialView(Views._CityList, db.CITIES.ToList());
}
[HttpPost]
// [AjaxOnly]
// [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public virtual ActionResult List2()
{
return PartialView(Views._CityList, db.CITIES.ToList());
}
public virtual ActionResult Edit()
{
int id = 1;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CITy city = db.CITIES.Find(id);
if (city == null)
{
return HttpNotFound();
}
// return View(city);
return PartialView(Views._Edit, city);
}
public virtual ActionResult RenderModalPartialView()
{
return PartialView(viewName: "_ModalPartialView", model: new CITy() { CITY_ABBR = "", CITY_NAME = "" });
}
[HttpPost]
//[AjaxOnly]
public virtual ActionResult Index(CITy user)
{
if (this.ModelState.IsValid)
{
//todo: SaveChanges;
return Json(new { success = true });
}
this.ModelState.AddModelError("", "Error");
return PartialView("_ModalPartialView", user);
}
}

The issue you have here is that you are adding validation to controller actions that do not need it. Let's start by looking at your Controller, you have:
// GET: /City/Edit/5
[ValidateAntiForgeryToken]
public virtual ActionResult Edit(int? id)
Which is requiring an anti-forgery token on a Get request. You would normally only include the [ValidateAntiForgeryToken] attribute on POST requests - they're used to stop somebody posting data to you without coming through your site. Check this tutorial for an overview.
Now coupled to this, any place where you have the [ValidateAntiForgeryToken] token you need to have a corresponding BeginForm with the HtmlHelper call #Html.AntiForgeryToken() in your View. In your code the edit link is 1) not in a form and 2) hasn't got this.
So in short: remove the [ValidateAntiForgeryToken] attribute from your GET requests in your controller and it should work fine.

Related

Validation of the form submitted by Ajaxform jQuery plugin in ASP.NET MVC 5

public class File
{
[Key]
public int FileID { get; set; }
[Display(Name = "atachfile")]
[MaxLength(150)]
public string atachFile{ get; set; }
}
I wrote the controller codes of the editing section like this...
// GET: /Users/FileUpload/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
File file = db.Files.Find(id);
if (file == null)
{
return HttpNotFound();
}
return View(file);
}
// POST: /Users/FileUpload/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "FileID,atachFile")] File file, HttpPostedFileBase LearnAtach , int id)
{
if (ModelState.IsValid)
{
if (LearnAtach != null)
{
if (file.atachFile != null)
{
System.IO.File.Delete(Server.MapPath("/File/LearnAtach/" + file.atachFile));
}
string[] FileExtension = { ".zip" };
string FileType = Path.GetExtension(LearnAtach.FileName);
double FileSize = (LearnAtach.ContentLength / 1024.0) / 1024;
if (FileExtension.Contains(FileType.ToLower()))
{
if (FileSize > 950)
{/
ViewBag.sizeatach = "error..filexize>950";
return View(file);
}
file.atachFile = Guid.NewGuid() + Path.GetExtension(LearnAtach.FileName);
LearnAtach.SaveAs(Server.MapPath("/File/LearnAtach/" + file.atachFile));
}
else
{
ViewBag.typeatach = "filyType != zip";
this.TempData["UnSuccessMessage"] = "filyType != zip";
return View(file);
}
}
fileRepository.UpdateFile(file);
fileRepository.save();
return RedirectToAction("Index");
}
return View(file);
}
View markup:
#model DataLayer.File
#using (Html.BeginForm("Edit", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data", id = "fileform" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.FileID)
<div class="form-group">
#Html.LabelFor(model => model.atachFile, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.atachFile, new { type = "file", Name = "LearnAtach" })
#Html.ValidationMessageFor(model => model.atachFile)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="submit" class="btn btn-success" />
</div>
</div>
</div>
}
<div class="progress progress-striped" style="direction: ltr">
<div class="progress-bar progress-bar-success">0%</div>
</div>
<br /><br />
#section scripts
{
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/modal.js"></script>
<script>
$(document).ready(function() {
var bar = $('.progress-bar');
var percent = $('.progress-bar');
var status = $('#status');
$("#fileform").ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
//show preloder
},
success: function() {
var percentVal = '100%';
bar.width(percentVal);
percent.html(percentVal);
//hide preloder
$("#Success").modal();
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
</script>
}
Now the file is uploaded but the validators are not applied .. How can I show the filesize limit and filetype the file on the client side to the user and apply
In fact, if the condition of file size and format is also wrong, the uploaded file will be saved in the (/File/LearnAtach)folder, but because the condition is incorrect, its path will not be stored in the database.
Also, if the condition is true, the condition whether this file already exists or deletes the previous one will not be checked. Thanks

how to fix EntityValidationErrors

I want to update user but whene I click on submit I get this error : EntityValidationErrors in this ligne :
Ligne 335 : context.SaveChanges();
I am using Entity Framework in ASP.NET MVC project:
this this my edit action in controller :
// GET: ApplicationUsers/Edit/2 :
[AuthLog(Roles = "Super Administrateur")]
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ApplicationUser user = context.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
// POST: ApplicationUsers/Edit/2
[AuthLog(Roles = "Super Administrateur")]
[HttpPost, ValidateInput(false), ActionName("Edit")]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,No_,RaisonSociale,Magasin,RemiseHabituelle,FamilyName,FirstName,EmailSup,Login,AffPrix,PasserCmd,EmailRespMagasin,Admin,BoursePR,Actif,IdSession,VendeurItirénant,ChargeClient,ValidOuAnnul,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] ApplicationUser applicationUser)
{
if (ModelState.IsValid)
{
context.Entry(applicationUser).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("ListUsers","Account");
}
return View(applicationUser);
}
this is the Edit View :
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Login, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Login, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Login, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Enregistrer" class="btn btn-default" />
</div>
</div>
</div>
}
The solution was : that UserName attributes is required.I find this error by adding block try {} catch {} to my edit action :
public ActionResult Edit([Bind(Include = "Id,No_,RaisonSociale,Magasin,RemiseHabituelle,FamilyName,FirstName,EmailSup,Login,AffPrix,PasserCmd,EmailRespMagasin,Admin,BoursePR,Actif,IdSession,VendeurItirénant,ChargeClient,ValidOuAnnul,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] ApplicationUser applicationUser)
{
if (ModelState.IsValid)
{
context.Entry(applicationUser).State = EntityState.Modified;
try
{
context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{ string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
// raise a new exception nesting
// the current instance as InnerException
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("ListUsers","Account");
}
return View(applicationUser);
}

How to add existing view with own controller as a partial view to another view?

i am using visual studio 2013 community edition.In my ASP.NET MVC application I had a view with model and controller as follows. I created the view from scafolding. It is database first approach. I added edmx file, then added controller with scafolding, which created views.
Model:
using System;
using System.Collections.Generic;
public partial class request
{
public request()
{
this.stocks = new HashSet<stock>();
this.transactions = new HashSet<transaction>();
}
public int request_id { get; set; }
public Nullable<long> request_no { get; set; }
public int request_status { get; set; }
public virtual ICollection<stock> stocks { get; set; }
public virtual ICollection<transaction> transactions { get; set; }
}
View:
#model MaterialManagement2.request
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>request</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.request_no, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.request_no, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.request_no, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.request_status, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.request_status, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.request_status, "", 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:
namespace MaterialManagement2.Controllers
{
public class requestsController : Controller
{
private MaterialManagement2Entities db = new MaterialManagement2Entities();
// GET: requests
public ActionResult Index()
{
return View(db.requests.ToList());
}
// GET: requests/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
request request = db.requests.Find(id);
if (request == null)
{
return HttpNotFound();
}
return View(request);
}
// GET: requests/Create
public ActionResult Create()
{
return View();
}
// POST: requests/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([Bind(Include = "request_id,request_no,request_status")] request request)
{
if (ModelState.IsValid)
{
db.requests.Add(request);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(request);
}
// GET: requests/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
request request = db.requests.Find(id);
if (request == null)
{
return HttpNotFound();
}
return View(request);
}
// POST: requests/Edit/5
// 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 Edit([Bind(Include = "request_id,request_no,request_status")] request request)
{
if (ModelState.IsValid)
{
db.Entry(request).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(request);
}
// GET: requests/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
request request = db.requests.Find(id);
if (request == null)
{
return HttpNotFound();
}
return View(request);
}
// POST: requests/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
request request = db.requests.Find(id);
db.requests.Remove(request);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
Now i need this view to be rendered as partial view with another view who has separate controller and model. I have created another view(partial) with above mentioned model with create template. This partial view called "_request" resides in shared folder. Now i used
#Html.Partial("_request", new MaterialManagement2.request())
in my another view so i can use them both is single view but the create button of the new view with partial view does not work. How do i make that button work?
Below is a screen shot of the app. The view renders correctly and looks exactly like i wanted. The button does not works though.
You have to specify the first controller name in this line :
#using (Html.BeginForm("Create", "requestsController"))
and you should drop this in the submit button:
value="Create"

Asp.Net MVC 5, View not posting back to the controller

I am creating a simple login form using Asp.Net MVC 5. Everything is fine but when I click on submit button after giving User Id and Password, the view does not go back to the desired Controller Action (LogIn). Here is the Action:
[HttpPost]
public ActionResult LogIn(User user)
{
var auth_user = CheckAuthentication(user);
if(auth_user!=null)
{
Session["user"] = new User() { UserId = user.UserId, Name = user.Name };
return RedirectToAction("Index", "User");
}
return View();
}
[AllowAnonymous]
public ActionResult LogIn()
{
return View();
}
and the view:
#model FinancialManagement.Models.User
#{
ViewBag.Title = "LogIn";
}
<h2>LogIn</h2>
#using (Html.BeginForm("LogIn", "User", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.UserId, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserId)
#Html.ValidationMessageFor(model => model.UserId)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Log In" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
This is my complete User controller:
[Authorize]
public class UserController : Controller
{
private FinancialManagmentEntities db = new FinancialManagmentEntities();
// GET: /User/
public ActionResult Index()
{
return View(db.Users.ToList());
}
// GET: /User/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
// GET: /User/Create
[AllowAnonymous]
public ActionResult Create()
{
return View();
}
// POST: /User/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(User user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
ActionResult LogOut()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
User CheckAuthentication(User user)
{
return db.Users.Where(u => u.UserId == user.UserId && u.Password == user.Password).FirstOrDefault();
}
[HttpPost]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public ActionResult LogIn(User user)
{
var auth_user = CheckAuthentication(user);
if(auth_user!=null)
{
Session["user"] = new User() { UserId = user.UserId, Name = user.Name };
return RedirectToAction("Index", "User");
}
return View();
}
[AllowAnonymous]
public ActionResult LogIn()
{
return View();
}
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
// POST: /User/Edit/5
// 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 Edit([Bind(Include="UserId,Name,Password")] User user)
{
if (ModelState.IsValid)
{
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
// GET: /User/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
// POST: /User/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
User user = db.Users.Find(id);
db.Users.Remove(user);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
Try to specify the View's Name and your Model like that :
return View("NameOfView", YourModel);
If it doesn't work put the absolute path :
return View("~/Views/FolderName/ViewName.cshtml");

Create Controller in MVC for comments and feedbacks

I have created a create controller for comments and feedback i have one issue with that , I cannot add new comments using that controller i.e. if i have already added a comment against some ID it will gives me option to edit that comments. But i want that it saves the old comments and allows me to add a new comment against that id. please help i am pasting my controller here.
public ActionResult CreateNote(int id)
{
YelloAdminDbContext db = new YelloAdminDbContext();
var feedBack = db.SaveFeedBack.Find(id);
if (feedBack != null && feedBack.feedback.FeedBackDrpDown == "Interested - Call Back After 1 month")
{
var temp = db.Note.Find(id);
if (temp != null)
{
temp.CallBAckDate = DateTime.Now.AddDays(36);
return View(temp);
}
else
{
return View(new CallNote { LoginId = id, FormFillDate = DateTime.Now, CallBAckDate = DateTime.Now.AddDays(30) });
}
}
if (feedBack != null && feedBack.feedback.FeedBackDrpDown == "Not Available - Call Back After One Day")
{
var temp = db.Note.Find(id);
if (temp != null)
{
temp.CallBAckDate = DateTime.Now.AddHours(15);
return View(temp);
}
else
{
return View(new CallNote { LoginId = id, FormFillDate = DateTime.Now, CallBAckDate = DateTime.Now.AddDays(1) });
}
}
if (feedBack != null && feedBack.feedback.FeedBackDrpDown == "Currently using yello - Call Back After Two Months")
{
var temp = db.Note.Find(id);
if (temp != null)
{
temp.CallBAckDate = DateTime.Now.AddDays(10);
return View(temp);
}
else
{
return View(new CallNote { LoginId = id, FormFillDate = DateTime.Now, CallBAckDate = DateTime.Now.AddMonths(2) });
}
}
return View(new CallNote { LoginId = id, FormFillDate = DateTime.Now, CallBAckDate = null});
}
public bool DoesExist(int loginId)
{
YelloAdminDbContext db = new YelloAdminDbContext();
if (db.Note.Find(loginId) == null)
{
return false;
}
return true;
}
[HttpPost]
public ActionResult CreateNote(CallNote callnote)
{
YelloAdminDbContext db = new YelloAdminDbContext();
//if (DoesExist(callnote.LoginId))
//{
// db.Entry(callnote).State = EntityState.Modified;
// db.SaveChanges();
// return JavaScript("alert('success');");
//}
//else
if (ModelState.IsValid)
{
db.Note.Add(callnote);
db.SaveChanges();
return Content("Success");
}
return Content("Error");
}
Here is create note view
#model MyYello.Admin.Models.CallNote
#{
ViewBag.Title = "CreateNote";
}
#*<body onload="JavaScript:AutoRefresh(30000);">*#
<body>
<h2>Comments and Feed Back</h2>
<div>
<h3>Curent Feed Back Value
<br />
#{Html.RenderAction("DisplayFeedBack", "Admin");}
</h3>
#{Html.RenderAction("SelectFeedBack", "Admin");}
</div>
#using (Html.BeginForm("CreateNote", "Admin", FormMethod.Post))
{#Html.ValidationSummary(true);
<fieldset>
#Html.HiddenFor(item => item.LoginId)
#Html.HiddenFor(item => item.FormFillDate)
<legend>Comments and Feedback</legend>
<div class="editor-label">
#Html.LabelFor(item => item.Comments, "Staff Comments")
</div>
<div class="editor-field">
#Html.TextAreaFor(item => item.Comments)
#Html.ValidationMessageFor(item => item.Comments)
</div>
<div class="editor-label">
#Html.LabelFor(item => item.FeedBackBox, "Custommer Feedback")
</div>
<div class="editor-field">
#Html.TextAreaFor(item => item.FeedBackBox)
#Html.ValidationMessageFor(item => item.FeedBackBox)
</div>
<div class="editor-label">
#Html.LabelFor(item => item.CallBAckDate, "Call Back Date")
</div>
<div class="editor-label">
#Html.TextBoxFor(item => item.CallBAckDate)
#Html.ValidationMessageFor(item => item.CallBAckDate)
</div>
<p>
<input type="Submit" value="Create" id="Create" />
</p>
</fieldset>
}
</body>
<script type="text/JavaScript">
<!--
function AutoRefresh(t) {
setTimeout("location.reload(true);", t);
}
</script>

Resources