Remote validation work but form not post - asp.net-mvc

I am using Remote validation on two field Email and CNIC.Remote Validation work proper but when i clik on submit button form not post.When i remove remote validation on both of fileds form post the data.
Model
Public class VMModel{
[Remote("Function","Controller",ErrorMessage = "The CNIC already exists")]
public string CNIC { get; set; }
[Remote("Function2", "Controller", ErrorMessage = "The Email already exists")]
public string Email { get; set; }
}
Controller
public JsonResult Function2(string Email)
{
bool IsExist = true;
if (Membership.GetUser(Email) != null)
{
IsExist = false;
}
return Json(IsExist, JsonRequestBehavior.AllowGet);
}
public JsonResult Function(string CNIC)
{
bool IsExist = true;
if (GetUserByCNIC(CNIC) != null)
{
IsExist = false;
}
return Json(IsExist, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Create(VMModel model)
{
return View(model);
}
View Code
<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("Create", "Controller", FormMethod.Post, new { enctype = "multipart/form-data"}))
{ %>
<fieldset>
<div class="inner_left">
<div class="editor-label">
<%: Html.LabelFor(m => m.Email)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.Email)%>
<%:Html.ValidationMessageFor(m => m.Email)%>
</div>
<div class="clear"></div>
<div class="editor-label">
<%: Html.LabelFor(m => m.CNIC)%>
</div>
<div class="editor-field">
<%: Html.EditorFor(m => m.CNIC)%>
<%:Html.ValidationMessageFor(m => m.CNIC)%>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<p style="text-align:left;margin-left: auto;margin-right: auto;width: 400px;">
<input type="submit" class="hrbutton" value="Create" />
</p>
</fieldset>
<% } %>

Related

How to make your button on a form using asp.net-mvc work?

I have a button, it does not seem to create new users to my database. What it does it only inherits user validaton to my Login method and need some guidance to this please and thanks. Below is the logic what i am trying to do. What i want to do my create button must be able to create new users if not exist to the database.
Controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateModel objSubmit)
{
ViewBag.Msg = "Details submitted successfully";
return View(objSubmit);
}
// This is for login, and its hits this method each time.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(Login login)
{
if (ModelState.IsValid)
{
bool success = WebSecurity.Login(login.username, login.password, false);
var UserID = GetUserID_By_UserName(login.username);
var LoginType = GetRoleBy_UserID(Convert.ToString(UserID));
if (success == true)
{
if (string.IsNullOrEmpty(Convert.ToString(LoginType)))
{
ModelState.AddModelError("Error", "Rights to User are not Provide Contact to Admin");
return View(login);
}
else
{
Session["Name"] = login.username;
Session["UserID"] = UserID;
Session["LoginType"] = LoginType;
if (Roles.IsUserInRole(login.username, "Admin"))
{
return RedirectToAction("AdminDashboard", "Dashboard");
}
else
{
return RedirectToAction("UserDashboard", "Dashboard");
}
}
}
else
{
ModelState.AddModelError("Error", "Please enter valid Username and Password");
return View(login);
}
}
else
{
ModelState.AddModelError("Error", "Please enter Username and Password");
return View(login);
}
}
Model:
namespace eNtsaPortalWebsiteProject.Models
{
public class CreateModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string password { get; set; }
[Required]
public string username { get; set; }
}
}
// View for login
<div data-="mainContent">
<section class="container">
<div class="logo col-sm-12 text-center col-md-12"> <img alt="" src="~/Images/eNtsa.png" /></div>
<div class="clearfix"></div>
<div class="container">
<div class="row">
<div id="MyWizard" class="formArea LRmargin">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div id="divMessage" class="text-center col-md-12 col-md-offset-12 alert-success">
#Html.ValidationSummary()
</div>
<div class="col-md-12 col-md-offset-10 col-xs-12">
<div class="loginPage panel-info">
<div class="form-group"><span class=""><i class="glyphicon glyphicon-user">Username:</i></span>
#Html.TextBoxFor(model => model.username, new { #class = "form-control text-center", autocomplete = "off" })
#Html.ValidationMessageFor(model => model.username)
</div>
<div class="form-group">
<span class=""><i class="glyphicon glyphicon-lock">Password:</i></span>
#Html.PasswordFor(model => model.password, new { #class = "form-control text-center", autocomplete = "off" })
#Html.ValidationMessageFor(model => model.password)
</div>
</div>
<div class="form-group">
<input id="BtnLogin" type="submit" class="btn btn-success btn-pressure" name="BtnLogin" value="Login" />
<input type ="Submit" class="btn btn-info btn-pressure" name="BtnCreate" value="Create" />
</div>
</div>
}
<div class="clear"></div>
</div>
</div>
</div>
</section>
</div>
View for creating user:
<div class="mainContent">
<section class="container">
<div class="logo col-sm-12 text-center col-md-10">
<img alt="" src="~/Images/eNtsa.png"/>
</div>
<div class="container">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div id="divMessage" class="text-center col-md-12 col-md-offset-12 alert-success">
#Html.ValidationSummary()
</div>
<div class="col-md-12 col-md-offset-10 col-xs-12">
<div class="glyphicon-registration-mark">
<div class="form-group"><span class=""><i class="glyphicon glyphicon-user">Username:</i></span>
#Html.TextBoxFor(model=>model.username, new {#class ="form-control text-center", automplete="off" })
#Html.ValidationMessageFor(model=>model.username)
</div>
<div class="form-group">
<span class=""><i class="glyphicon glyphicon-lock">Password:</i></span>
#Html.PasswordFor(model=>model.password, new {#class = "form-control text-center", autocomplete="off" })
#Html.ValidationMessageFor(model=>model.password)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-success btn-pressure" name="BtnSubmit" value="Submit"/>
</div>
</div>
}
</div>
</section>
</div>
The button is working - that isn't the problem that you're having.
You can have multiple buttons to submit the form but they will return to the same place, either:
a) the controller/action specified in the "action" property of the form
b) if no action is specified then the default location - in your case there isn't one directly specified so it is posting back to the default location.
(see: How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4)
The easiest way to accomplish what you're trying to do would be refactor your controller and branch the logic depending on what the value is of the submit button.
(see: MVC razor form with multiple different submit buttons?
and How to handle two submit buttons on MVC view)
This will require some refactoring of the code that you have written, but it is the most straightforward way of achieving what you're trying to do.
In very basic terms it would look something like this:
Model:
namespace eNtsaPortalWebsiteProject.Models
{
public class LoginCreateModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string password { get; set; }
[Required]
public string username { get; set; }
public string btnSubmit { get; set; } // both buttons will have the same name on your form, with different values ("Create" or "Login")
}
}
Controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginCreateModel objSubmit)
{
if (objSubmit.btnSubmit == "Create")
{
// Handle creation logic here
}
if (objSubmit.btnSubmit == "Login")
{
// Handle login logic here
}
return View(objSubmit);
}

How to retain formcollection values on postback in MVC

Here I am using simple application and on clicking send button I will execute Index httppost action. But for some reason if my captcha is not correct then i am trying to load the same view. I am passing form collection so my firstname and lastname are not wiped out. Please suggest how can i persist my values.
[HttpPost]
public ActionResult Index(FormCollection dataColl)
{
ColComments datgrp = new ColComments();
datgrp.fname = dataColl[0].ToString();
datgrp.lname = dataColl[1].ToString();
if (!this.IsCaptchaValid(""))
{
ViewBag.Classname = "alert alert-warning";
ViewBag.ErrorMessage = "Incorrect captcha answer.";
}
else
{
ViewBag.ErrorMessage = "OKAY";
return RedirectToAction("Landing", "Account");
}
return View(dataColl);
}
Index view.
#using CaptchaMvc.HtmlHelpers
#model CaptchaTestApp.Models.ColComments
#{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p>Learn more ยป</p>
</div>
<div>
#using (Html.BeginForm())
{
<div> #Html.ValidationSummary(true)</div>
<fieldset>
<legend>ColComments</legend>
<div class="editor-label">
#Html.LabelFor(model => model.fname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.fname)
#Html.ValidationMessageFor(model => model.fname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.lname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.lname)
#Html.ValidationMessageFor(model => model.lname)
</div>
</fieldset>
<table>
<tr>
<td colspan="3">
#Html.Captcha(8, "_captchaCnt")
</td>
</tr>
</table>
<p>
<input type="submit" value="Send" />
</p>
}
</div>
You need to return the same view which you are sending in HttpGet method with updated values. You are sending form collection object to view.
[HttpPost]
public ActionResult Index(FormCollection dataColl)
{
ColComments datgrp = new ColComments();
datgrp.fname = dataColl[0].ToString();
datgrp.lname = dataColl[1].ToString();
if (!this.IsCaptchaValid(""))
{
ViewBag.Classname = "alert alert-warning";
ViewBag.ErrorMessage = "Incorrect captcha answer.";
}
else
{
ViewBag.ErrorMessage = "OKAY";
return RedirectToAction("Index", "Home");
}
return View(datgrp);
}

How to find an item in my database?

So i want to create a person and add it to my table if i dont have the same name already in my table. i have this code in my controller
hesaplamaEntities hsb = new hesaplamaEntities();
[HttpPost]
public ActionResult Create(MyTable p)
{
MyTable obj = hsb.MyTable.Find(p);
if (obj.propname == null)
{
hsb.MyTable.Add(p);
hsb.SaveChanges();
return RedirectToAction("Create", "Home");
}
else
{
return HttpNotFound();
}
and this is my View :
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { #class =
"form-horizontal", enctype = "multipart/form-data" }))
{
<div class="row">
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-12">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
#Html.TextBoxFor(m => m.propname, new { #class = "form-control" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="col-sm-2 control-label">kod</label>
<div class="col-sm-10">
#Html.TextAreaFor(m => m.propkod, new { #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-sm-9 col-sm-offset-3">
<div class="btn-toolbar pull-right">
<input type="submit" value="save" class="btn btn-primary" />
</div>
</div>
</div>
</div>
}
and this is my Model :
public partial class MyTable
{
public int ID { get; set; }
public string propkod { get; set; }
public string propname { get; set; }
}
i am having this error when i am trying to add person :
he specified parameter type 'WebApplication7.Models.MyTable' is not valid. Only scalar types, such as System.Int32, System.Decimal, System.DateTime, and System.Guid, are supported.
and its showing me the error in this line : HesapTemel obj = hsb.HesapTemels.Find(p);
what is the probleme exactly ?

After submit a form in a Area not displayed none of validation message?

I have a area and at this area i have a PostController, and a action with Add name for GET method and a action with Add name for POST method,after submit form i add error to modelstate BUT after postback,not displayed none of validation message and staus code is:301 Moved Permanently !!!
my viewmodel:
public class NewPostViewModel
{
[Required(ErrorMessage = "Please enter title.")]
public string Title { get; set; }
[AllowHtml]
[Required(ErrorMessage = "Please enter article content.")]
public string Content { get; set; }
[Required(ErrorMessage = "Please enter a tag.")]
public string Tags { get; set; }
public bool PublishNow { get; set; }
public string PublishDate { get; set; }
public string PublishTime { get; set; }
}
my view:
#model Soleimanzadeh.Models.ViewModels.NewPostViewModel
#{
ViewBag.Title = "Add";
Layout = MVC.Admin.Shared.Views.BaseLayout;
}
#using (Html.BeginForm(MVC.Admin.Post.Add(), FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(false, null, new { #class = "alert" })
<div class="row-fluid">
<div class="span9">
<div class="row-fluid">
<div class="span8">
#Html.TextBoxFor(np => np.Title, new { #class = "span12", placeholder = "Title" })
#Html.ValidationMessageFor(model=>model.Title)
</div>
</div>
<div class="row-fluid">
<div class="span12">
#Html.TextAreaFor(np => np.Content)
#Html.ValidationMessageFor(model=>model.Content)
</div>
</div>
</div>
<div class="span3">
<div class="row-fluid">
<div class="post-options-container">
<div class="header">
Tags
</div>
<div class="content">
<input type="text" placeholder="tags" class="tagManager" style="width: 100px;" />
</div>
</div>
</div>
<div class="row-fluid">
<div class="post-options-container">
<div class="header">
Status
</div>
<div class="content">
<label class="checkbox">
#Html.CheckBoxFor(np => np.PublishNow)
Publish Now?
</label>
<div>
Publish Date:
#Html.TextBoxFor(np => np.PublishDate, new { #class = "calcInput" })
</div>
<div>
Publish Time:
#Html.TextBoxFor(np => np.PublishTime, new { #class = "timeInput" })
</div>
<div>
<input type="submit" value="Save"/>
</div>
</div>
</div>
</div>
</div>
</div>
}
#*some scripts here*#
my controller:
public partial class PostController : Controller
{
public virtual ActionResult Add()
{
var newPost = new NewPostViewModel();
return View(MVC.Admin.Post.Views.Add, newPost);
}
[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult Add(NewPostViewModel post)
{
ModelState.AddModelError("Content","Wrong");
return this.View(MVC.Admin.Post.Views.Add, post);
}
}
Also i use redactor html editor for Content.
Solution:
i use http://lowercaseroutesmvc.codeplex.com/ for convert urls to lowercase,but i not enabled this tool in area section and page redirectd after submit form.

ASP.NET MVC File Upload Error - "The input is not a valid Base-64 string"

I'm trying to add a file upload control to my ASP.NET MVC 2 form but after I select a jpg and click Save, it gives the following error:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
Here's the view:
<% using (Html.BeginForm("Save", "Developers", FormMethod.Post, new {enctype = "multipart/form-data"})) { %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
Login Name
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.LoginName) %>
<%: Html.ValidationMessageFor(model => model.LoginName) %>
</div>
<div class="editor-label">
Password
</div>
<div class="editor-field">
<%: Html.Password("Password") %>
<%: Html.ValidationMessageFor(model => model.Password) %>
</div>
<div class="editor-label">
First Name
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FirstName) %>
<%: Html.ValidationMessageFor(model => model.FirstName) %>
</div>
<div class="editor-label">
Last Name
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.LastName) %>
<%: Html.ValidationMessageFor(model => model.LastName) %>
</div>
<div class="editor-label">
Photo
</div>
<div class="editor-field">
<input id="Photo" name="Photo" type="file" />
</div>
<p>
<%: Html.Hidden("DeveloperID") %>
<%: Html.Hidden("CreateDate") %>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
And the controller:
//POST: /Secure/Developers/Save/
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(Developer developer)
{
//get profile photo.
var upload = Request.Files["Photo"];
if (upload.ContentLength > 0)
{
string savedFileName = Path.Combine(
ConfigurationManager.AppSettings["FileUploadDirectory"],
"Developer_" + developer.FirstName + "_" + developer.LastName + ".jpg");
upload.SaveAs(savedFileName);
}
developer.UpdateDate = DateTime.Now;
if (developer.DeveloperID == 0)
{//inserting new developer.
DataContext.DeveloperData.Insert(developer);
}
else
{//attaching existing developer.
DataContext.DeveloperData.Attach(developer);
}
//save changes.
DataContext.SaveChanges();
//redirect to developer list.
return RedirectToAction("Index");
}
Thanks,
Justin
I have recently found a solution for this, although I am now using MVC3 rather than MVC2.
In the Save action, exclude the binary field from the bound object and include a separate HttpPostedFileBase field:
e.g.
public ActionResult Save([Bind(Exclude = "Photo")]Developer developer, HttpPostedFileBase Photo) {...}
Note that you can also do this to avoid having to include the Html.Hidden elements from your View. e.g.:
public ActionResult Save([Bind(Exclude = "Photo,DeveloperID,CreateDate")]Developer developer, HttpPostedFileBase Photo) {...}
You can then use this HttpPostedFileBase object directly rather than needing to access Request.Files.
Personally, I actually store these types of images in the database in an SQL "image" field using this code:
if (Picture != null)
{
if (Picture.ContentLength > 0)
{
byte[] imgBinaryData = new byte[Picture.ContentLength];
int readresult = Picture.InputStream.Read(imgBinaryData, 0, Picture.ContentLength);
Developer.Picture = imgBinaryData;
}
}
Hope this is helpful...
Mark
I just tried your code and was able to upload without any issues. I did not save to the database nor does my Developer class have a Photo property.
namespace MvcApplication5.Controllers
{
public class Developer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime UpdateDate { get; set; }
public int DeveloperID { get; set; }
public string LoginName { get; set; }
public string Password { get; set; }
}
}
Controller
public class DefaultController : Controller
{
//
// GET: /Default/
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(Developer developer)
{
//get profile photo.
var upload = Request.Files["Photo"];
if (upload.ContentLength > 0)
{
string savedFileName = Path.Combine(
#"C:\temp",
"Developer_" + developer.FirstName + "_" + developer.LastName + ".jpg");
upload.SaveAs(savedFileName);
}
developer.UpdateDate = DateTime.Now;
if (developer.DeveloperID == 0)
{//inserting new developer.
}
else
{//attaching existing developer.
}
//save changes.
//redirect to developer list.
return RedirectToAction("Index");
}
}
View
<div>
<% using (Html.BeginForm("Save", "Default", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ %>
<%: Html.ValidationSummary(true)%>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
Login Name
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.LoginName)%>
<%: Html.ValidationMessageFor(model => model.LoginName)%>
</div>
<div class="editor-label">
Password
</div>
<div class="editor-field">
<%: Html.Password("Password")%>
<%: Html.ValidationMessageFor(model => model.Password)%>
</div>
<div class="editor-label">
First Name
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FirstName)%>
<%: Html.ValidationMessageFor(model => model.FirstName)%>
</div>
<div class="editor-label">
Last Name
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.LastName)%>
<%: Html.ValidationMessageFor(model => model.LastName)%>
</div>
<div class="editor-label">
Photo
</div>
<div class="editor-field">
<input id="Photo" name="Photo" type="file" />
</div>
<p>
<%: Html.Hidden("DeveloperID")%>
<%: Html.Hidden("CreateDate")%>
<input type="submit" value="Save" />
</p>
</fieldset>
<%} %>
</div>
I got the same issue. here is the solution I found.
Class property:
public byte[] Logo { get; set; }
View Code:
#using (Html.BeginForm("StoreMyCompany", "MyCompany", FormMethod.Post, new { id = "formMyCompany", enctype = "multipart/form-data" }))
{
<div class="form-group">
#Html.LabelFor(model => model.modelMyCompany.Logo, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6">
<input type="file" name="Logo" id="fileUpload" accept=".png,.jpg,.jpeg,.gif,.tif" />
</div>
</div>
}
Controller Code:
public ActionResult StoreMyCompany([Bind(Exclude = "Logo")]MyCompanyVM model)
{
try
{
Company objCompany = new Company();
byte[] imageData = null;
if (Request.Files.Count > 0)
{
HttpPostedFileBase objFiles = Request.Files["Logo"];
using (var binaryReader = new BinaryReader(objFiles.InputStream))
{
imageData = binaryReader.ReadBytes(objFiles.ContentLength);
}
}
}
catch (Exception ex)
{
Utility.LogError(ex);
}
return View();
}
}
i just excluded Logo from controller's call.
I have the same error, but the solution above didn't work for me, instead I notice that my Model property name is the same as the parameter name I am passing with the controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditSOP(File file, HttpPostedFileBase Upload)
My Model property name is
public byte[] Upload { get; set; }
After renaming it on a different parameter name, it now works:
public ActionResult EditSOP(File file, HttpPostedFileBase UploadFile)

Resources