Create Controller in MVC for comments and feedbacks - asp.net-mvc

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>

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

MVC redirect to error page doesn't display message

In MVC I am trying to redirect a message to an Error page when it occurs. The Error Page will open but I get no error message.
This is the method that initiates the process.
[HttpPost]
public ActionResult SaveSurvey(vmFollowUpSurvey model)
{
var result = surveyBL.postSurveyResults(model);
if (result != "Record Saved")
{
ModelState.AddModelError(string.Empty, "Survey not saved");
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Error");
return Json(new { Url = redirectUrl });
}
else
{
ModelState.AddModelError(string.Empty, "Survey completed");
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Login");
return Json(new { Url = redirectUrl });
}
}
My ErrorController then has a method of
public ActionResult Index()
{
return View();
}
And my View displays as this
<h2>Survey Information Page</h2>
<div>
#using (Html.BeginForm("Index", "Error"))
{
<div class="container">
<div class="row">
#Html.ValidationSummary(false, "", new { #class = "text-info" })
</div>
</div>
}
</div>
So what did I not do to get this to display?
Your ErrorController.Index() method has no knowledge of the model being used, so adding the message to ModelState will mean your error page doesn't have access to it. If you're going to be redirecting to a different view, the proper way to handle this would be to put the error inside the Session.
if (result != "Record Saved")
{
Session["Error"] = "Survey not saved";
...
}
Then inside your Error view, you can do something like this:
<h2>Survey Information Page</h2>
<div>
#using (Html.BeginForm("Index", "Error"))
{
<div class="container">
<div class="row">
<span class="error-message">#Session["Error"]</span>
</div>
</div>
}
</div>
[HttpPost]
public ActionResult SaveSurvey(vmFollowUpSurvey model)
{
var result = surveyBL.postSurveyResults(model);
if (result != "Record Saved")
{
return RedirectToAction("Index", "Error", new { ErrorMessage= "Survey not saved"} );
}
else
{
ModelState.AddModelError(string.Empty, "Survey completed");
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Login");
return Json(new { Url = redirectUrl });
}
}
--- ErrorModel Class
namespace WebApplication3.Models
{
public class ErrorModel
{
public string ErrorMessage { get; set; }
}
}
--- Error Index.html code
#model WebApplication3.Models.ErrorModel
<h2>Survey Information Page</h2>
<div>
#using (Html.BeginForm("Index", "Error"))
{
<div class="container">
<div class="row">
#Html.ValidationSummary(false, Model.ErrorMessage , new { #class = "text-info" })
</div>
</div>
}
</div>

MVC Error : Object reference not set to an instance of an object on #Html.ValidationSummary

Always got an error and I can't really figure out what part of my code generates this error ? I tried to compare it to the other situations in the internet still can't trace what's going on. Can somebody share me your suggestions ??
Here's my View :
#model StockroomMaitenance.Models.PG_User
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<p>
<a href="#Url.Action("Users", "Admin", new { id = Model.User_Id })" data-original-title="Back to List" data-toggle="tooltip">
<i class="glyphicon glyphicon-th-list"></i>Back to List</a>
</p>
<fieldset>
<legend>PG_User</legend>
<div class="editor-label">
#Html.LabelFor(model => model.User_Id)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.User_Id)
#Html.ValidationMessageFor(model => model.User_Id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.User_BadgeId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.User_BadgeId)
#Html.ValidationMessageFor(model => model.User_BadgeId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.User_FullName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.User_FullName)
#Html.ValidationMessageFor(model => model.User_FullName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.User_Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.User_Email)
#Html.ValidationMessageFor(model => model.User_Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.User_Role, "PG_Role")
</div>
<div class="editor-field">
#Html.DropDownList("User_Role", String.Empty)
#Html.ValidationMessageFor(model => model.User_Role)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.User_Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.User_Password)
#Html.ValidationMessageFor(model => model.User_Password)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
And heres my model:
public partial class PG_User
{
public PG_User()
{
this.PG_UserAct = new HashSet<PG_UserAct>();
this.PG_Role1 = new HashSet<PG_Role>();
}
public int User_Id { get; set; }
public string User_BadgeId { get; set; }
public string User_FullName { get; set; }
public Nullable<int> User_Role { get; set; }
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
public string User_Password { get; set; }
public string User_Email { get; set; }
public virtual PG_Role PG_Role { get; set; }
public virtual ICollection<PG_UserAct> PG_UserAct { get; set; }
public virtual ICollection<PG_Role> PG_Role1 { get; set; }
}
And here is my controller
public ActionResult Users(string sortUser, string searchString)
{
if (Session["LoggedUserRole"] == null && Session["LoggedUserFullname"] == null)
{
return RedirectToAction("Error", "Login");
}
else
{
ViewBag.NameSort = String.IsNullOrEmpty(sortUser) ? "User_FullName" : "";
ViewBag.BadgeSort = sortUser == "User_BadgeId" ? "user_desc" : "User_BadgeId";
var pg_user = db.PG_User.Include(p => p.PG_Role);
if (!String.IsNullOrEmpty(searchString))
{
pg_user = pg_user.Where(s => s.User_FullName.Contains(searchString));
if (pg_user != null)
{
pg_user = pg_user.Where(s => s.User_FullName.Contains(searchString));
}
else
{
ViewBag.NotFound = "No Results Found";
}
}
switch (sortUser)
{
case "User":
pg_user = pg_user.OrderByDescending(s => s.User_FullName);
break;
case "User_BadgeId":
pg_user = pg_user.OrderBy(s => s.User_BadgeId);
break;
case "user_desc":
pg_user = pg_user.OrderByDescending(s => s.User_BadgeId);
break;
default:
pg_user = pg_user.OrderBy(s => s.User_FullName);
break;
}
return View(pg_user.ToList());
}
}
//
// GET: /Admin/Details/5
public ActionResult Details(int id = 0)
{
if (Session["LoggedUserRole"] == null && Session["LoggedUserFullname"] == null)
{
return RedirectToAction("Error", "Login");
}
else
{
PG_User pg_user = db.PG_User.Find(id);
if (pg_user == null)
{
return HttpNotFound();
}
return View(pg_user);
}
}
//
// GET: /Admin/Create
public ActionResult Create()
{
if (Session["LoggedUserRole"] == null && Session["LoggedUserFullname"] == null)
{
return RedirectToAction("Error", "Login");
}
else
{
ViewBag.User_Role = new SelectList(db.PG_Role, "Role_Id", "Role_Description");
return View();
}
}
//
// POST: /Admin/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PG_User pg_user)
{
if (Session["LoggedUserRole"] == null && Session["LoggedUserFullname"] == null)
{
return RedirectToAction("Error", "Login");
}
else
{
if (ModelState.IsValid)
{
db.PG_User.Add(pg_user);
db.SaveChanges();
return RedirectToAction("Users");
}
ViewBag.User_Role = new SelectList(db.PG_Role, "Role_Id", "Role_Description", pg_user.User_Role);
return View(pg_user);
}
}
//
// GET: /Admin/Edit/5
public ActionResult Edit(int id = 0)
{
if (Session["LoggedUserRole"] == null && Session["LoggedUserFullname"] == null)
{
return RedirectToAction("Error", "Login");
}
else
{
PG_User pg_user = db.PG_User.Find(id);
if (pg_user == null)
{
return HttpNotFound();
}
ViewBag.User_Role = new SelectList(db.PG_Role, "Role_Id", "Role_Description", pg_user.User_Role);
return View(pg_user);
}
}
Notices something wrong ??
For anyone with the same issue stumbling upon this question, here's the answer.
Because of the first line in your view, #model StockroomMaitenance.Models.PG_User, this is a strong typed view.
You have to pass an instance of PG_User to the view.
So in the controller action public ActionResult Create(), you should change
return View(); to
return View(new PG_User());
I am not sure why the exception is thrown on #Html.ValidationSummary, but I have tested this modification and it solves the issue (needed to remove code referencing PG_Role and PG_UserAct, first).

ASP.MVC The required anti-forgery form field errors

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.

How to create view for given model

I am new to asp .net mvc 4.0. i have given model. i am not getting how can i create view for model. I am facing problem at IList JournalEntries. other entry i am able to do.
public class Journal : BaseClass
{
public virtual string VoucherNo { get; set; }
public virtual DateTime VoucherDate { get; set; }
public string VoucherDateView {
get
{
return VoucherDate.ToShortDateString();
}
}
public IList<JournalEntry> JournalEntries { get; set; }
public IList<Ledger> Accounts { get; set; }
public double TotalAmount
{
get
{
double sum = 0;
if (JournalEntries != null && JournalEntries.Count>0)
foreach (var journal in JournalEntries)
sum = journal.Principal + journal.Interest+sum;
return sum;
}
}
}
I have tried below view but add entry doesn't works.
#model Sms.CoreSociety.Journal
#{
ViewBag.Title = "Create";
}
#{
string data = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model);
}
<script type="text/javascript">
$(document).ready(function () {
$('#document').validate();
$("#VoucherDate").mask("99/99/9999", { placeholder: " " });
function entryVm(entries) {
var self = this;
self.entryList = ko.observableArray(entries);
self.entry = ko.observable();
self.rowClick = function(entry1) {
alert("Delete alert");
self.dispatchList.remove(entry1);
};
self.addEntry = function() {
alert("Add alert");
this.entryList.push({ AccountName_AccountHead: "", DebitCredit: "", Principal: "0.0", Interest: "0.0", Narration: ""});
};
}
var models = #Html.Raw(Json.Encode(Model.JournalEntries)) ;
ko.applyBindings(new entryVm(models));
});
</script>
#using (Html.BeginForm(null, null, FormMethod.Post, new Dictionary<string, object>() { { "class", "form-horizontal" }, { "id", "document" } }))
{
#Html.ValidationSummary(true)
<fieldset>
<div class="row">
<div class="span1">
<label>Voucher No</label>
</div>
<div class="span5">
#Html.DisplayFor(model => model.VoucherNo)
</div>
</div>
<div class="row">
<div class="span1">
<label>Voucher Date</label>
</div>
<div class="span5">
#Html.TextBoxFor(model => model.VoucherDate, "{0:dd/MM/yyyy}", new Dictionary<string, object>() { { "class", "required" } })
</div>
</div>
<div class="row">
<div class="span1">
<label>Amount</label>
</div>
<div class="span5">
#Html.DisplayFor(model => model.TotalAmount)
</div>
</div>
<input type="submit" value="Save" class="btn" id="submit"/>
#if (Model.Id != new Guid())
{
<div style="float: right">
<a class="btn btn-danger" href='#Url.Action("Delete")/#Model.Id' aria-hidden="true">Delete</a>
</div>
}
</fieldset>
}
<h4>Journal Entry</h4>
<p >Entry for<span data-bind="text: entryList().length"> </span> entry(s)</p>
<button data-bind="click: addEntry" class="btn">Add Record</button>
<table>
<tbody data-bind="template: { name: 'entryRowTemplate', foreach: entryList }"></tbody>
</table>
<script type="text/html" id="entryRowTemplate">
<tr>
<td>AccountName_AccountHead: \$ <input data-bind="value: AccountName.AccountHead"/> </td>
<td>DebitCredit: \$ <input data-bind="value: DebitCredit"/></td>
<td>Principal: \$ <input data-bind="value: Principal"/></td>
<td>Interest: \$ <input data-bind="value: Interest"/></td>
<td>Narration: \$ <input data-bind="value: Narration"/></td>
<td>Delete</td>
</tr>
</script>
below is my Journal controller
using System;
using System.Linq;
using System.Web.Mvc;
using Sms.CoreSociety;
using System.Collections.Generic;
namespace SmsModernUI.Controllers
{
public class JournalController : BaseController
{
//
// GET: /AccountGroup/
public ActionResult Index()
{
var journals = Repository.GetAll<Journal>().OrderBy(x => x.VoucherNo);
return View(journals);
}
public ActionResult Create(Guid id)
{
if (id == new Guid())
{
var journal = new Journal();
string lastvoucherno = Repository.GetAll<Journal>().OrderBy(x => x.VoucherNo).Last().VoucherNo;
journal.VoucherNo = (int.Parse(lastvoucherno) + 1).ToString();
journal.VoucherDate = System.DateTime.Now;
journal.JournalEntries = new List<JournalEntry>();
journal.Accounts = Repository.GetAll<Ledger>();
return PartialView(journal);
}
var journal1 = Repository.Get<Journal>(id);
journal1.JournalEntries = Repository.GetAll<JournalEntry>(x => x.Journal.Id == id);
journal1.Accounts = Repository.GetAll<Ledger>();
return PartialView(journal1);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(Journal journal)
{
if (journal.Id == new Guid())
{
var jj = Repository.Save(journal);
foreach (var journalentry in journal.JournalEntries)
{
journalentry.Id = jj.Id;
Repository.Save(journalentry);
}
}
else
{
Journal jr = Repository.Get<Journal>(journal.Id);
var entries = Repository.GetAll<JournalEntry>(x=>x.Journal.Id == journal.Id);
foreach (var entry in entries)
{
Repository.Delete(entry);
}
var jj = Repository.Save(journal);
foreach (var journalentry in journal.JournalEntries)
{
journalentry.Id = jj.Id;
Repository.Save(journalentry);
}
}
return RedirectToAction("Index");
}
public ActionResult Index1()
{
Journal journal1 = Repository.Get<Journal>(new Guid("7A6EEBBC-2F3A-4A27-ACF8-A1D40115A68F"));
journal1.JournalEntries = Repository.GetAll<JournalEntry>(x => x.Journal.Id == journal1.Id);
journal1.Accounts = Repository.GetAll<Ledger>();
return View(journal1);
}
public ActionResult Delete(Guid id)
{
Journal jr = Repository.Get<Journal>(id);
var entries = Repository.GetAll<JournalEntry>(x => x.Journal.Id == jr.Id);
foreach (var entry in entries)
{
Repository.Delete(entry);
}
var result = Repository.Delete(jr);
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Create1(Journal journal)
{
var temp = journal;
return RedirectToAction("Create",journal.Id);
}
}
}
Views are not genereted from models. You need Controller Action method to pass your model to View.
public ActionResult()
{
var model = new Journal
{
//**define here value of model's properties, that you need in View
}
return View(model);
}
EDITED: After your addition.
I would devide it into two parts. Create ViewModel and pass it from View To Controller.
public JurnalViewModel
{
public Journal journal {get; set;}
public IList<JournalEntry> JournalEntries {get; set;}
}
Than in Create action first create journal and after foreach JournalEntries in model create new JournalEntry.
EDITED 2 To your comment. Quick sample:
[HttpPost]
public ActionResult Create (JurnalViewModel model)
{
var journal = new Journal();
db.Journals.Add(journal);
journal.name = model.journal.name
.....
//**some code
db.SaveChanges()
foreach(var item in model.JournalEntries )
{
var entry = new JournalEntry()
db.JournalEntries .Add(entry);
entry.property = item.property;
....
//**some code
db.SaveChanges()
}
}
Your problem is that you have no class constructor for JournalEntries.
public Journal()
{
JournalEntries = new List<JournalEntry>();
Accounts = new List<Ledger>();
}
Right click to your Action method inside controller and click add view then check create strongly typed-view checkbox then choose your desired model from dropdown in displayed dialogue box

Resources