I have a partial view of saving email in newsletter mailing list that is used in Main partial view of the site. when click on its button, it should send form to services.js ,then send to action for saving in Database. But it saves "null" in it, when I set a break point on action, it doesn't go with it. what should i do?
Newsletter Model:
public class NewsletterModel
{
[Required(ErrorMessage = "Please enter your email address!")]
[Display(Name = "Email")]
public string Email { get; set; }
public Int16 LanguageId { get; set; }
}
partial view code:
#model Orinus.Models.NewsletterModel
<script src="#Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<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>
<link href="../../Content/Default/Site.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/Services.js" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<br />
<p>
<input type="button" value="Register" id="saveEmailNewsletter" class="ButtonStyle"/>
</p>
}
This is the action code:
[HttpPost]
public ActionResult Index(NewsletterModel newsLetter)
{
if (!ModelState.IsValid)
{
return PartialView("_Newsletter", newsLetter);
}
SaveEmailForNewsletterSrv newsLetterSrv = new SaveEmailForNewsletterSrv();
newsLetterSrv.SaveEmailForNewsletter(newsLetter);
return Json(new { success = true });
}
}
this code is for Services.js:
/// <reference path="jquery-1.7.1.min.js" />
$(function () {
$("#saveEmailNewsletter").click(function () {
var email = $("#Email").val();
var language = 1;
newsLetter = { 'Email': email,'Language': language };
if (dat == null) {
alert("Please enter your email address!");
return;
}
$.ajax({
url: '/Newsletter/Index',
type: 'POST',
dataType: 'json',
data: newsLetter,
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.success) {
// We have a JSON object in case of success
Alert ('Successfully registered...');
} else {
// We have the partial with errors in case of failure
// so all we have to do is update the DOM
$('#resultMessage').dialog(result);
}
}
});
})
});
Related
I need to get a list permissao when I select a group, I made the methods but when I select the group, it returns me an error.
PermissaoGrupo/ObterPermissoesAdd:1 Failed to load resource: the
server responded with a status of 400 ()
View
#model RKMES.Models.ViewModel.PermissaoGrupoViewModel
<script type="text/javascript" src="assets/js/plugins/forms/inputs/duallistbox.min.js"></script>
<script type="text/javascript" src="assets/js/pages/form_dual_listboxes.js"></script>
<h2>Index</h2>
<div class="form-group">
#*<label asp-for="Grupos" class="control-label">Grupo</label>*#
#*<select class="custom-select custom-select-sm" asp-items="#(new SelectList(Model.Grupos,"Id","Nome"))"></select>*#
Grupos
#Html.DropDownList("Grupos", new SelectList(Model.Grupos,"Id", "Nome"))
</div>
<!-- Filtered results -->
<div class="panel panel-flat">
<div class="panel-heading">
<h5 class="panel-title">Filtered results</h5>
</div>
<div class="panel-body">
#*<select multiple="multiple" class="form-control listbox-no-selection" asp-items="#(new SelectList(Model.Permissoes,"Id","Nome"))"></select>*#
#Html.DropDownList("Permissoes", new SelectList(Enumerable.Empty<SelectListItem>(), "Id", "Nome"))
</div>
</div>
<!-- /filtered results -->
<script type="text/javascript">
$(document).ready(function () {
$('#Grupos').change(function () {
var idGrupo = $('#Grupos').val();
if (idGrupo > 0) {
$.post('#Url.Action("ObterPermissoesAdd", "PermissaoGrupo")', { 'idGrupo': idGrupo }, function (data) {
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
$('#Permissoes').append('<option value="' +data[i].Id+ '">' + data[i].Nome+ '</option>');
}
}
});
}
});
});
</script>
PermissaoGrupoController
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ObterPermissoesAdd(int idGrupo)
{
return Json(_grupoContext.GetPermissoesAdd(idGrupo));
}
GrupoService
public async Task<List<Permissao>> GetPermissoesAdd(int id)
{
return await _context.Grupo_Permissao_Permissao
.Where(x => x.Grupo_PermissaoId == id)
.Select(x => x.Permissao)
.ToListAsync();
}
Model
namespace RKMES.Models
{ // essa é uma tabela intermediaria das entidades Grupo_Permissao e Permissao
public class Grupo_Permissao_Permissao
{
public int Id { get; set; }
public int Grupo_PermissaoId { get; set; }
public int PermissaoId { get; set; }
public virtual Grupo_Permissao Grupo_Permissao { get; set; }
public virtual Permissao Permissao { get; set; }
}
}
What am I doing wrong?
For your issue, it is caused by ValidateAntiForgeryToken. which will check whether the request contains RequestVerificationToken header.
For a quick test, you could remove [ValidateAntiForgeryToken] from Controller.
For a recommended way, you need to attach the anti forgery token like
<script type="text/javascript">
$(document).ready(function(){
var Group = {
GroupId: 1,
GroupName: "My Group Name"
};
AjaxPost("/Groups/AddGroup", Group).done(function () {
GetGroups();
});
});
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
function AjaxPost(url, data) {
return $.ajax({
type: "post",
contentType: "application/json;charset=utf-8",
dataType: "json",
responseType: "json",
url: url,
headers: {
"RequestVerificationToken": gettoken()
},
data: JSON.stringify(data)
});
}
</script>
I am trying to send date to controller using ajax but get's null. why?
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="~/Scripts/jquery-2.2.0.min.js"></script>
<script src="~/Scripts/moment.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$('#datetimepicker1').datetimepicker({ useCurrent: false });
$('#datetimepicker1').on("dp.hide", function (e) {
$.ajax({
url: "/Home/GetData",
type: "POST",
data: JSON.stringify($('#datetimepicker1').data('DateTimePicker').date()),
contentType: "application/json",
success: function (result) { alert('Done') },
error: function (r, e, s) { alert(e) }
});
});
</script>
</div>
</div>
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult GetData(string test)
{
return View();
}
}
You not passing a name/value pair back to the controller method that matches the parameter name (test) and the is no need to stringify the data. Change the ajax script to
$.ajax({
url: '#Url.Action("GetData", "Home")', // don't hard code your url's
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date() },
// contentType: "application/json", delete this
success: function (result) { alert('Done') },
error: function (r, e, s) { alert(e) }
});
And since you posting a DateTime value the controller method should be
[HttpPost]
public ActionResult GetData(DateTime test)
{
return View();
}
This assumes the the date value is in a format that matches the server culture, or in ISO format ('yyyy-MM-dd HH:mm'), for example by using
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
Note that your method is returning a view, but you not doing anything with the html you return (just displaying an alert)
I'm using C# asp.net mvc4 and trying to do ajax search. But ther is error and it says " The resource cannot be found.".
What I'm doing wrong?
Controller
//Search
[HttpPost]
public ActionResult ContractSearch(string Name)
{
var contracts = db.Contracts.Include(c => c.DocType).Include(c => c.CreditType).Include(c => c.Bank).Include(c => c.UserProfile).Where(c => c.FirstName.Equals(Name));
return View(contracts.ToList());
}
View
#model IEnumerable<CreditoriyaApp.Models.Contract>
#{
ViewBag.Title = "Index";
}
<div>
#using (Ajax.BeginForm("ContractSearch", "Contract", new AjaxOptions { UpdateTargetId = "searchresults" }))
{
<input type="text" name="Name" />
<input type="submit" value="Search" />
}
<div id="searchresults">
#if (Model != null && Model.Count()>0)
{
<ul>
#foreach (var item in Model)
{
<li>#item.FirstName</li>
}
</ul>
}
</div>
Error
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Contract/ContractSearch
Add the below in your controller. Then your error will be corrected.
public ActionResult ContractSearch()
{
return View();
}
for searching you can try something like below example.
Model:
public class Person
{
public string Name { get; set; }
public string Country { get; set; }
}
Controller:
public ActionResult SearchPerson()
{
return View();
}
[HttpPost]
public ActionResult SearchPerson(string searchString)
{
System.Collections.Generic.List<Person> lst = new List<Person>();
lst.Add(new Person { Name = "chamara", Country = "Sri Lanka" });
lst.Add(new Person { Name = "Arun", Country = "India" });
if (!string.IsNullOrEmpty(searchString))
{
lst = lst.AsEnumerable().Where(r => r.Name.Contains(searchString)).ToList();
}
string result = string.Empty;
result = "<p>Search Result<p>";
foreach (Person item in lst)
{
result = result + "<p> Names is: " + item.Name + " and Country is:" + item.Country + "<p>";
}
return Content(result, "text/html");
}
View:
#model IEnumerable<Mvc4Test.Models.Person>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>SearchPerson</title>
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
</head>
<body>
#using (Ajax.BeginForm("SearchPerson", "Search", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "searchresults" }))
{
#Html.TextBox("searchString")
<input type="submit" value="Search" />
}
<div id="searchresults">
</div>
</body>
</html>
In my class file where my model is I have required attributes such as:
[Required]
[Range(0, 99, ErrorMessage = "Sorry, you must select a range between 0 - 99.")]
public int MaxConcurrentUsers { get; set; }
So you would think that when I click the submit button on the page to post the values, that because I have typed an incorrect value for MaxConcurrentUsers it wouldn't reach the actionResult method in my C# code. But it does. One thing I have noticed is that my modelstate .valid is false, but I want the client to stop it from getting to that method. What am I doing wrong?
My model
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace UserManager.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class vw_UserManager_Model
{
public string rowtype { get; set; }
public System.Guid applicationid { get; set; }
public System.Guid userid { get; set; }
// [StringLength(12, MinimumLength = 6,
//ErrorMessage = "Username must be between 6 and 12 characters.")]
public string UserName { get; set; }
[Required]
[Range(0, 99, ErrorMessage = "Sorry, you must select a range between 0 - 99.")]
public int MaxConcurrentUsers { get; set; }
[Required(ErrorMessage = "First name is a required field")]
[Display(Name = "First name")]
public string firstname { get; set; }
[Required(ErrorMessage = "Last name is a required field")]
[Display(Name = "Last name")]
public string lastname { get; set; }
public string salutation { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string password { get; set; }
[Required(ErrorMessage = "Email is required.")]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string email { get; set; }
public string group_name { get; set; }
public Nullable<long> group_id { get; set; }
public int moduleid { get; set; }
public Nullable<int> session_status { get; set; }
public Nullable<int> islockedout { get; set; }
public Nullable<bool> isactive { get; set; }
public bool IsApproved { get; set; }
public bool alf { get; set; }
public bool brad { get; set; }
public string module_name { get; set; }
public string CompanyName { get; set; }
public string CompanySearch { get; set; }
public string selected_module { get; set; }
public string selected_group { get; set; }
public string selected_moduleAlf { get; set; }
public string selected_moduleBrad { get; set; }
public string selected_groupAlf { get; set; }
public string selected_groupBrad { get; set; }
}
}
My view
#model UserManager.Models.vw_UserManager_Model
<h2 style="padding-left: 25px;">
Create user</h2>
#using (Html.BeginForm())
{
<!-- ALF/BRAD selection -->
#Html.ValidationSummary(true)
<fieldset style="width: 400px; padding-left: 15px;">
<legend>Select module type:</legend>
<div class="module-selection">
#Html.Label("Select ALF")
<input type="checkbox" checked="checked" id="chkAlf" name="selection" value="Alf"
onclick="chkSelection()" />
#Html.Label("Select BRAD")
<input type="checkbox" id="chkBrad" name="selection" value="Brad" onclick="chkSelection()" />
</div>
</fieldset>
<!-- Module selection -->
<fieldset style="width: 400px; padding-left: 15px;">
<legend>Select module:</legend>
<div id="alfModules">
#{Html.RenderAction("_CreateUserModulesAlf", "UserManager");}
</div>
<br />
<div id="bradModules">
#{Html.RenderAction("_CreateUserModulesBrad", "UserManager");}
</div>
</fieldset>
<!-- Check if group exists -->
<fieldset style="width: 400px; padding-left: 15px;">
<legend>Group Checker</legend>
<div id="createuser-groupnamesearch">
#{Html.RenderAction("_txtGroupSearchForm", "UserManager");}
</div>
</fieldset>
<fieldset style="width: 400px; padding-left: 15px;">
<legend>New User Details</legend>
<div class="editor-label">
#Html.LabelFor(Model => Model.salutation)
</div>
<div class="editor-field">
#Html.DropDownListFor(Model => Model.salutation, new List<SelectListItem>
{
new SelectListItem{ Text="Mr", Value = "Mr" },
new SelectListItem{ Text="Mrs", Value = "Mrs" },
new SelectListItem{ Text="Miss", Value = "Miss" },
new SelectListItem{ Text="Ms", Value = "Ms" },
new SelectListItem{ Text="Dr", Value = "Dr" }
})
#Html.ValidationMessageFor(model => Model.salutation)
</div>
<div id="createuser-usernamesearch">
#{Html.RenderAction("_txtUsernameSearch", "UserManager");}
</div>
<div class="editor-label">
#Html.Label("Firstname")
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.firstname)
#Html.ValidationMessageFor(model => Model.firstname)
</div>
<div class="editor-label">
#Html.Label("Surname")
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.lastname)
#Html.ValidationMessageFor(model => Model.lastname)
</div>
<div class="editor-label">
#Html.Label("Password")
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.password)
#Html.ValidationMessageFor(model => Model.password)
</div>
<div class="editor-label">
#Html.Label("Email")
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.email)
#Html.ValidationMessageFor(model => Model.email)
</div>
<div class="editor-label">
#Html.Label("Is active")
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.isactive)
#Html.ValidationMessageFor(model => Model.isactive)
</div>
<div class="editor-label">
#Html.Label("Maximum concurrent users")
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.MaxConcurrentUsers)
#Html.ValidationMessageFor(model => Model.MaxConcurrentUsers, "Enter a number between 0-99.")
</div>
<div id="moduleSelection">
#Html.HiddenFor(Model => Model.selected_moduleAlf, new { id = "hdnModuleAlf" })
#Html.HiddenFor(Model => Model.selected_moduleBrad, new { id = "hdnModuleBrad" })
</div>
<input type="submit" value="Create" onclick="return submitWith();" />
<span id="validationMessage"></span>
<br />
<br />
#Html.ActionLink("Back to List", "Index")
</fieldset>
<div>
#Html.ValidationSummary()
</div>
}
<script type="text/javascript">
// Count checkboxes that are checked.
function submitWith() {
var checkedCount = $("input:checked").length;
var valid = checkedCount > 0;
// Check that one checkbox is checked first
if (!valid) { // IF false
$('#validationMessage').html('You must select at least one option').css("background-color", "red");
}
// Second check ALF
else if ($('.module-selection #chkAlf').is(':checked')) {
if ($("#txtGroupnameExistsAlf").val() == "Alf Group doesn't exist.") {
valid = false;
$('#validationMessage').html('Group must exist in ALF Database first').css("background-color", "red");
}
if ($("#txtGroupnameExistsAlf").val() == "") {
valid = false;
$('#validationMessage').html('A group must be picked when creating a new user.').css("background-color", "red");
}
}
// Third check
else if ($('.module-selection #chkBrad').is(':checked')) {
if ($("#txtGroupnameExistsBrad").val() == "Brad Group doesn't exist.") {
valid = false;
$('#validationMessage').html('Group must exist in BRAD Database first').css("background-color", "red");
}
if ($("#txtGroupnameExistsBrad").val() == "") {
valid = false;
$('#validationMessage').html('A group must be picked when creating a new user.').css("background-color", "red");
}
}
else {
valid = true;
}
return valid;
}
function chkSelection() {
// alert("check selection");
filters = new Object();
if ($('.module-selection #chkAlf').is(':checked')) {
// Show Div
$("#alfModules").show();
$("#groupname-checker-alf").show();
// Show username checker for Alf
$("#username-checker-alf").show();
// Set ALF model property to true
$("#hdnAlf").val("true");
// Set alf value for one to be passed to Ajax request
filters.alf = 1;
var selectedVal = $("#ddlSelectedAlf :selected").val();
$('#hdnModuleAlf').val(selectedVal);
}
else {
$("#alfModules").hide();
$("#groupname-checker-alf").hide();
$("#hdnAlf").val("false");
$("#username-checker-alf").hide();
filters.alf = 0;
$('#hdnModuleAlf').val("false");
$("#txtGroupnameExistsAlf").val("").css("background-color", "white");
}
if ($('.module-selection #chkBrad').is(':checked')) {
// Show Div
$("#bradModules").show();
$("#groupname-checker-brad").show();
// Show username checker for Alf
$("#username-checker-brad").show();
// Set alf value for one to be passed to Ajax request
filters.brad = 1;
var selectedVal = $("#ddlSelectedBrad :selected").val();
$('#hdnModuleBrad').val(selectedVal);
}
else {
$("#bradModules").hide();
$("#groupname-checker-brad").hide();
$("#hdnBrad").val("false");
$("#username-checker-brad").hide();
filters.brad = 0;
$('#hdnModuleBrad').val("false");
$("#txtGroupnameExistsBrad").val("").css("background-color", "white");
}
filters.username = $('#createuser-usernamesearch #user_name').val();
return filters;
}
function searchUsername() {
var filters = chkSelection();
$.ajax({
url: '#Url.Action("UsernameSearch", "UserManager")',
type: "POST",
async: true,
dataType: "json",
data: "username=" + filters.username,
success: function (data) {
var usernameExistsAlf = parseInt(data.usernameAlf);
if (usernameExistsAlf > 0) {
$('#txtUsernameExistsAlf').val("Username already exists").css("background-color", "red");
}
else {
$('#txtUsernameExistsAlf').val("Username doesn't exist").css("background-color", "#33ff00");
}
var usernameExistsBrad = parseInt(data.usernameBrad);
if (usernameExistsBrad > 0) {
$('#txtUsernameExistsBrad').val("Username already exists").css("background-color", "red");
}
else {
$('#txtUsernameExistsBrad').val("Username doesn't exist").css("background-color", "#33ff00");
}
},
error: function (data) {
}
});
}
$("#group_name").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("LookUpGroupName", "UserManager")',
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
value: request.term
},
success: function (data) {
response($.map(data, function (item) {
// alert(item.group);
return {
label: item.group,
value: item.group
} // end of return
})); // end of response
}, // end of success
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
} // end of error
}); // end of ajax
},
minLength: 2,
select: function (event, ui) { // Assign to hidden values to trigger onchange ajax call.
$.ajax({
url: '#Url.Action("GroupnameCheck", "UserManager")',
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
value: ui.item.label
},
success: function (data) {
$.each(data, function (index, value) {
if (index == "AlfGroup") {
$("#txtGroupnameExistsAlf").val(value);
if ($("#txtGroupnameExistsAlf").val() == "Alf Group doesn't exist.") {
$("#txtGroupnameExistsAlf").css("background-color", "red");
}
else {
$('#txtGroupnameExistsAlf').css("background-color", "#33ff00");
}
}
if (index == "BradGroup") {
$("#txtGroupnameExistsBrad").val(value);
if ($("#txtGroupnameExistsBrad").val() == "Brad Group doesn't exist.") {
$("#txtGroupnameExistsBrad").css("background-color", "red");
}
else {
$('#txtGroupnameExistsBrad').css("background-color", "#33ff00");
}
}
});
}, // end of success
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
} // end of error
}); // end of ajax
$('#hdnGroupAlf').val(ui.item.label);
$('#hdnGroupBrad').val(ui.item.label);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
$(document).ready(function () {
chkSelection();
});
</script>
My layout with all the scripts
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<!-- Javascript -->
<script src="../../Scripts/jquery-1.8.3.min.js" type="text/javascript"></script>
#* <script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>*#
<script src="#Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
#* <script src="#Url.Content("~/Scripts/jquery.autocomplete.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/Custom/autocompleteGroup.js")" type="text/javascript"></script>*#
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<!-- Javascript -->
<!-- Stylesheets -->
<link href="#Url.Content("~/Content/themes/base/jquery.ui.autocomplete.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/themes/base/jquery.ui.autocomplete.custom.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<!-- Stylesheets -->
</head>
<body>
<div class="page">
<div id="header">
<div id="title" >
<h1>ALF and BRAD User Manager</h1>
</div>
<div id="logindisplay">
<span style="color:Black; background-color:white; text-align:right;">
Logged in as: <strong>#Context.User.Identity.Name</strong>
</span>
</div>
<nav>
<ul id="menu">
#Html.ActionLink("User Manager Dashboard", "Index", "UserManager")  
#Html.ActionLink("User Analytics", "Index", "UserStatus")  
#Html.ActionLink("Email Distibution", "Index", "EmailDistributionList")  
#Html.ActionLink("Email User Details", "Index", "EmailUserDetails")  
</ul>
</nav>
</div>
<section id="main">
#RenderBody()
</section>
<footer>
</footer>
</div>
</body>
</html>
#* <script type="text/javascript">
$(document).ready(function () {
doAutocomplete('#Url.Action("LookUpGroupName", "UserManager")');
});
</script>*#
So any help? Thanks!
This is how it should work. You will still get to the method, but can check the ModelState to decide what to do, for example...
if (ModelState.IsValid) {
// Save, redirect to action
}
return View(model); // send them back to correct the problem!
You will also be able to display the errors on the view, as they will be present. You can use a ValidationSummary or have individual ValidationFor elements.
Check the below link. It may help you.
Client side validation
Update:
You need to enable clientside validation, unobtrusivejavascript and refer the script files in master page.
[web.config]
<appSettings>
<add key="webpages:Version" value="1.0.0.0" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
[layout.cshtml]
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
I have the following form in a partial view
#model PartDetail
#using (Ajax.BeginForm("Create", "Part", null, new AjaxOptions { UpdateTargetId = "update_panel"}))
{
<h3>New #Model.PartType</h3>
<p> Serial Number:
<strong>
#Html.EditorFor(model => model.SerialNumber)
#Html.ValidationMessageFor(model => model.SerialNumber)
</strong>
</p>
<p> Name:
<strong>
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</strong>
</p>
...... more relatively boiler plate code here......
<p>
<input type="submit" class="btn primary" value="Save Part"/>
</p>
}
With a model of
public class PartDetail
{
public string DateCreated { get; set; }
[StringLength(255, MinimumLength = 3)]
public string Description { get; set; }
public Guid ID { get; set; }
public string IsActive { get; set; }
public string Manufacturer { get; set; }
public IEnumerable<SelectListItem> Manufacturers { get; set; }
[StringLength(100, MinimumLength = 3)]
public string Name { get; set; }
public string PartType { get; set; }
[Required]
[StringLength(100, MinimumLength = 3)]
public string SerialNumber { get; set; }
}
And I reference (in parent views of my partial view)
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"> </script>
And nothing gets validated. If I type nothing into the Serial Number text box and press submit it saves it to the database with no problems.
Try adding an OnBegin callback to the AjaxOptions and this should work.
function validateForm() {
return $('form').validate().form();
}
#using (Ajax.BeginForm("Create", "Part", null, new AjaxOptions { UpdateTargetId = "update_panel", OnBegin = "validateForm" }))
...
If this doesn't work for you, an alternative solution may be to submit the form using jQuery. This would be my preferred solution.
<div id="result"></div>
#using (Html.BeginForm())
{
<h3>New #Model.PartType</h3>
<p>Serial Number:
<strong>
#Html.EditorFor(model => model.SerialNumber)
#Html.ValidationMessageFor(model => model.SerialNumber)
</strong>
</p>
<p> Name:
<strong>
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</strong>
</p>
...... more relatively boiler plate code here......
<p>
<input type="submit" class="btn primary" value="Save Part"/>
</p>
}
jQuery/JS function to submit the form
$(function () {
$('form').submit(function () {
$.validator.unobtrusive.parse($('form')); //added
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
In this case order of javascript file including process is important. Your order of including these file should be
jquery.js
jquery.validate.js
jquery.validate.unobtrusive.js
When I tried with re-ordering it works fine for me. Try it.
Check your root Web.config of the solution/project. Does it contain the following lines?
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
It not, add them.
you need to modified your controller action little bit to work validation in Ajax request
you catch RenderHtml of partial view and apply your validation on it for e.g
//In Controller
public string Create(PartDetail model)
{
string RenderHtml = RenderPartialViewToString("PartailViewName", model);
return RenderHtml;
}
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
you must be pass ViewName and Model to RenderPartialViewToString method. it will return you view with validation which are you applied in model.