The webpage cannot be found after submit my info - c#

I have view which name is thanks and I want to show this view after click submit , but its encounter with error like this:The webpage cannot be found
Here is my code:
public class HomeController : Controller
{
public ViewResult Index()
{
int hour = DateTime.Now.Hour;
ViewBag.greeting = hour < 12 ? "Good Morning" : "Good Afternoon";
return View ("MyView");
}
[HttpGet]
public ViewResult RsvpForm()
{
return View("RsvpForm");
}
[HttpPost]
public ViewResult RsvpForm(GuestRespons GuestRespons)
{
Repository.AddResponse(GuestRespons);
return View("Thanks", GuestRespons);
}
}
and this is my view :
#{Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>
Thanks
</title>
</head>
<body>
<p>
<h1>
thank you,#Model.Name!
</h1>
#if (Model.WillAttend== true)
{
#:it's great that you are comming.we will see you soon.
}
else
{
#:Sorry to hear that, but Thanks for letting us to know.
}
</p>
<p >
click <a asp-action="ListResponses">here</a> to see who is coming.
</p>
</body>
</html>
And this one is my button which should show thanks view:
#model FuturGoals_partyinvites_.Models.GuestRespons
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>RsvpForm</title>
</head>
<body>
<form asp-action="RcvpForm" method="post">
<p>
<label asp-for="Name">Your Name:</label>
<input asp-for="Name" />
</p>
<p>
<label asp-for="Email">Your Email:</label>
<input asp-for="Email" />
</p>
<p>
<label asp-for="phone">Your Phone:</label>
<input asp-for="phone" />
</p>
<p>
<label>Will you come?</label>
<select asp="WillAttend">
<option value="">Choose an option</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
</p>
<button type="submit">Submit RSVP</button>
</form>
</body>
</html>
well I don't know how get exception in mvc , I think problem should be with this line:
<button type="submit">Submit RSVP</button>
Thanks in advance.

Your form action attribute value should be a valid url in your app. If you are using the form tag helper, you need to make sure you are passing the valid HttpPost action method name you want to submit to, as the asp-action attribute value.
In your case, your http post action method name is RsvpForm, But in your form you had RcvpForm which is not a valid action method. So fix your form tag helper to use the correct action method and now it should work.
<form asp-action="RsvpForm" method="post">
<!-- Your existing form elements goes here-->
</form>

Do it something like:
<p>
<label asp-for="Name">Your Name:</label>
<input asp-for="Name" />
</p>
<p>
<label asp-for="Email">Your Email:</label>
<input asp-for="Email" />
</p>
<p>
<label asp-for="phone">Your Phone:</label>
<input asp-for="phone" />
</p>
<p>
<label>Will you come?</label>
<select asp="WillAttend">
<option value="">Choose an option</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
</p>
<button type="Button" id="submitme" data-url="#Url.Action("RsvpForm","Home")">Submit RSVP</button>
Ajax form like:
$("#submitme").on("click", function () {
var url = $(this).data('url');
$.ajax({
type: 'post',//this can be change to get or post
url: url,
success: function (response) {
if (response != null && response.success) {
Alert("Success");
window.location.href = "/Home/ActionNameHere"; //You can redirect any action name here....
} else {
// DoSomethingElse()
Alert("something wrong");
}
}
});
});

Related

Button click in ASP.NET MVC

I am trying to understand how this ASP.NET MVC thing works compared to webforms, so I tried to simply call any method that will do the most basic thing, print some text into console, or change the text of a label.
Turns out it's nearly damn impossible to do, so I tried to look it up, everything I could find requires to first make the method in the controller which can be fine, but then it requires to add the corresponding cshtml file, put some tags over there and when you click that thing you will get the page from the new cshtml, but that's not what I want, an example how it's done from what I was able to find.
In HomeController:
namespace WebApplication9.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult ClickTest()
{
ViewBag.Message = "ClickTest.";
Debug.WriteLine("Damn...");
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
In Views -> Shared -> _Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" title="more options">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })
</div>
<div id="test-nav" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Click", "ClickTest", "Home")</li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
The last step is to add ClickTesty.cshtml in Views -> Home, but that's not at all what I want to do, and all the examples of a click that I was able to find show this approach, except they do other things, but what if I just want to change a label text or hide something on a current page not a new one? I couldn't find any info how to do it using C#, in webforms there's no problem to change some text or hide something on the current page, even using javascript, but here I can't find a way.
To see a Debug.WriteLine in Visual Studio here's what you can do:
Add this code:
<input type="button" value="Click here to debug log" onclick="location.href='#Url.Action("ClickTest", "Home")'" />
Inside the "main" tag on your application
HomeController should look something like this:
public IActionResult ClickTest()
{
Debug.WriteLine("Damn...");
return View("Index");
}
Run the application in Debug mode (F5 by default)
Go to the Home page, click the button 'Click here to debug log'
You will see at the Output pane your Debug.WriteLine
What you are doing right now on your code is to redirect to a different view that doesn't exists. So, returning the View("Index") is doing the trick to not have an error and see your log.

Can not get [HttpPost] response

just started to learn the ASP MVC, I'm trying to make this form where you give your name and email and .... and when you click on submit Form, it should lead to the "Thanks" page where you see a thanks message and your name.
but after clicking on "Submit" Button nothing happened for me. I want to know what is the problem.
this is the Homecontroller for all action methods
using System;
using Microsoft.AspNetCore.Mvc;
using PartyInvites.Models;
namespace PartyInvites.Controllers
{
public class HomeController : Controller
{
public ViewResult Index()
{
int hours = DateTime.Now.Hour;
ViewBag.Greeting = hours < 12 ? "Good Morning" : "Good Evening";
return View("MyView") ;
}
[HttpGet]
public ViewResult RsvpForm()
{
return View();
}
[HttpPost]
public ViewResult RsvpForm(GuestResponse guestResponse)
{
Repository.AddResponse(guestResponse);
return View("Thanks",guestResponse);
}
}
}
this is "MyView" page , which is the default page
#{
Layout = null;
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<div>
#ViewBag.Greeting World (from the view)
<p>
We are going to have an exciting party.<br />
(to do:sell it better.Add pictures or something.)
</p>
<a asp-action="RsvpForm"> Ravp Now</a>
</div>
</body>
</html>
}
this is the Form page which you can go there after clicking on Ravp Now
*#
#model PartyInvites.Models.GuestResponse
#{ Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewpot" content="width=device-width"/>
<title>RsvpForm</title>
</head>
<body>
<form asp-action="RsvpForm" method="post"></form>
<p>
<label asp-for="Name"> Your Name: </label>
<input asp-for="Name"/>
</p>
<p>
<label asp-for="Email"> Your Email:</label>
<input asp-for="Email"/>
</p>
<p>
<label asp-for="Phone"> Your Phone:</label>
<input asp-for="Phone"/>
</p>
<p>
<label> Will You Attend?</label>
<select asp-for="WillAttend">
<option value=""> Choose an option </option>
<option value="true"> Yes, I'll be There. </option>
<option value="false"> No, i can't come. </option>
</select>
</p>
<button type="submit"> Submit Rsvp</button>
</body>
</html>
Now the problem is here when I click on Submit Rsvp , Nothing happens.it won't go to the "Thanks" page. I checked all codes a few times but couldn't find anything.
What could be wrong?
these are the "Thanks" View Page and "Repository" class model
#model GuestResponse
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head >
<meta name="viewport" content="width=device-width"/>
<title>Thanks</title>
</head>
<body>
<p>
<h1> Thank you! #Model.Name!</h1>
#if (Model.WillAttend == true)
{
#:Its great that you're coming.The drinks are already in the Fridge!
}
else
{
#:sorry to here that you can't make it , but thanks for letting us know.
}
</p>
<p> click<a asp-action="ListResponses"> here </a> to see who is coming.</p>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PartyInvites.Models
{
public static class Repository
{
private static List<GuestResponse> responses=new List<GuestResponse>();
public static IEnumerable<GuestResponse> Responses
{
get { return responses; }
}
public static void AddResponse(GuestResponse response)
{
responses.Add(response);
}
}
}
I think your issue is inside your cshtml file.
All contents of a form must be within such form declaration. I don't have a C# project available to check it right now, but I think the "fixed" code would be something like this:
*#
#model PartyInvites.Models.GuestResponse
#{ Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewpot" content="width=device-width"/>
<title>RsvpForm</title>
</head>
<body>
<form asp-action="RsvpForm" method="post">
<p>
<label asp-for="Name"> Your Name: </label>
<input asp-for="Name"/>
</p>
<p>
<label asp-for="Email"> Your Email:</label>
<input asp-for="Email"/>
</p>
<p>
<label asp-for="Phone"> Your Phone:</label>
<input asp-for="Phone"/>
</p>
<p>
<label> Will You Attend?</label>
<select asp-for="WillAttend">
<option value=""> Choose an option </option>
<option value="true"> Yes, I'll be There. </option>
<option value="false"> No, i can't come. </option>
</select>
</p>
<button type="submit"> Submit Rsvp</button>
</form>
</body>
</html>

ASP.NET MVC BeginForm not able to post with parameter

I have a form with a searchbox on it. When someone types something into the search box and hits the search button I am trying ot do a post to capture the search filter and then fire off a view.
Here is the controller code
public class SpotsController : Controller
{
[HttpPost]
[AllowAnonymous]
public ActionResult SearchSpots(string searchfilter)
{
//your code here....
return Index(searchfilter);
}
Here is the code from my view up until the part that is tryign to do the submit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - Haunt Spotter</title>
</head>
<form id="__AjaxAntiForgeryForm" action="#" method="post"><#Html.AntiForgeryToken()></form>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse">
#using (Html.BeginForm("SearchSpots", "Spots"))
{
<input id="searchfilter" type="text" class="form-control" autocomplete="off" placeholder="Search" name="searchfilter">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
}
</div>
</div>
</div>
If I take the parameter off of the controller function it works fine. If not it seems to crash and try to re display a get which fails because I only have a post function for this. I am guessing I have something screwed up with the parameter but I can't figure out what it is. Any help woudl be greatly appreciated.
UPDATE
Based on feedback I have changed my post to a get
[HttpGet]
[AllowAnonymous]
public ActionResult SearchSpots(string searchfilter)
{
//your code here....
return Index(searchfilter);
}
and my view code to this
#using (Html.BeginForm("SearchSpots", "Spots", FormMethod.Get, null))
{
<input id="searchfilter" type="text" class="form-control" autocomplete="off" placeholder="Search" name="searchfilter">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
}
Unfortunately I still have the original issue. If I remove the searchfileter parameter from my controller call then it goes into the call with no problems but when I am expecting the modelbinder to give me a searchfilter it crashes out.
Here is the call I am redirecting to in my search function
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Spots
public ActionResult Index(string filter = "")
{
ViewBag.initialFilter = filter;
if (User.IsInRole("SiteAdmin"))
{
return View(db.Spots.ToList());
}
else
{
return View(db.Spots.Where(x => x.Approved).ToList());
}
}
and the view that is displayed
#model IEnumerable<HauntSpots.Models.Spot>
#{
ViewBag.Title = "Index";
}
<h2 class="align-right">Haunt Spots</h2>
#if (Context.User.IsInRole("SiteAdmin"))
{
<p style="padding-top:20px">
<i class="icon-plus-sign"></i> Add New
</p>
}
<table id="dt-spots" class="table table-striped">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
#if (Context.User.IsInRole("SiteAdmin"))
{
<th></th>
}
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#if (Context.User.IsInRole("SiteAdmin"))
{
#Html.Hidden(Url.Action("Edit", "Spots", new { id = item.Id }))
<a style="color: Red; vertical-align: middle; font-size: 2em" href="#Url.Action("Delete", "Spots", new { id = item.Id })" title="Delete Spot" class="btn"><i class="icon-remove-sign"></i></a>
}
else
{
#Html.Hidden(Url.Action("Details", "Spots", new { id = item.Id }))
}
</td>
<td>
#if (item.Image == null)
{
<img width="100" height="100"
src="~/Content/Images/NoPhoto.jpg" class="img-rounded" />
}
else
{
<img width="100" height="100"
src="#item.Image" class="img-rounded"/>
}
</td>
<td >
<div class="form-group pull-left col-md-2">
<h4>#item.Title </h4>
<h5 style="clear: left">
#if (item.Address != null)
{
<span>#item.Address</span>
<br/>
}
#if (item.State == null)
{
<span>#item.City</span><br/>
<span>#item.Country</span>
}
else
{
if (item.State == "")
{
<span>#item.City</span>
<br/>
<span>#item.Country</span>
}
else
{
<span>#item.City, #item.State</span>
<br/>
<span>#item.Country</span>
}
}
</h5>
</div>
<div class="form-group pull-left col-md-8">
<h6>#item.Summary</h6>
</div>
</td>
#if (Context.User.IsInRole("SiteAdmin"))
{
<td>
#if (#item.Approved)
{
<span style="color: green">Approved</span>
}
else
{
<span style="color: red">Not Approved</span>
}
</td>
}
</tr>
}
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
//Initalize and configure DataTables
$('#dt-spots').dataTable({
"oSearch": { "sSearch": "#ViewBag.initialFilter" }
});
$("tbody").on("click", "tr", function () {
window.location = $(this).find('input').attr('name');
});
});
</script>
Do a GET instead of a POST—you're not doing any inserts or updates, just fetching results based on a parameter (searchfilter). With a GET, the values of the input elements in your form will be appended as parameters to the query string of the target URL, which would produce something like mywebsite.com/spots/spotsearch?searchfilter=whateverValueInTheInputBox (depending on how you have your routing configured).
Razor:
#using (Html.BeginForm("SearchSpots", "Spots", FormMethod.Get, null))
{
<input id="searchfilter" type="text" class="form-control" autocomplete="off" placeholder="Search" name="searchfilter">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
}
Controller:
public class SpotsController : Controller
{
[HttpGet]
[AllowAnonymous]
public ActionResult SearchSpots(string searchfilter)
{
// ...
}
}
Edit: As per #BviLLe_Kid, you can try replacing <button> with <input>.
Edit 2: Can't help but wonder why you are proxying the call to Index via SearchSpots, causing an unnecessary redirect. If all that SearchSpots does is redirect to Index, why not submit the form directly to Index?
Razor:
#using (Html.BeginForm("Index", "Spots", FormMethod.Get, null))
{
<!-- remember to rename to name="filter" below -->
<input id="filter" type="text" class="form-control" autocomplete="off" placeholder="Search" name="filter">
<input class="btn btn-default" type="submit" <i class="glyphicon glyphicon-search"</i>/>
}
Controller:
// GET: Spots
public ActionResult Index(string filter = "")
{
ViewBag.initialFilter = filter;
if (User.IsInRole("SiteAdmin"))
{
return View(db.Spots.ToList());
}
else
{
return View(db.Spots.Where(x => x.Approved).ToList());
}
}
In agreement with most of the other answers stating that this needs to be an HttpGet request rather than an HttpPost request I believe that this can be solved by changing your HTML.
HTML:
#using (Html.BeginForm("SearchSpots", "Spots", FormMethod.Get, null))
{
<input id="searchfilter" type="text" class="form-control" autocomplete="off" placeholder="Search" name="searchfilter">
<input class="btn btn-default" type="submit" <i class="glyphicon glyphicon-search"</i>/> // part that needs changing
}
Controller:
[HttpGet]
public ActionResult SearchSpots(string searchfilter)
{
// logic
}
I believe your issue can be related to this. <button> is exactly what it is.. a button.. it basically does nothing, and is mainly used for JS purposes. However, the <input type="submit" /> actually submits the surrounding form.
I hope this helps!
UPDATE
I did need the input to pass the parameter. I still had the same error even after it was being passed and I had to make this final tweak to get it running
[HttpGet]
[AllowAnonymous]
public ActionResult SearchSpots(string searchfilter)
{
return RedirectToAction("Index", new { filter = searchfilter});
}
I needed to redirect instead of trying to return a view
I believe you're missing FormMethod.Post in
#using (Html.BeginForm("SearchSpots", "Spots", FormMethod.Post))
{...
you don't need two forms in your HTML and this code is working and post search text
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - Haunt Spotter</title>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse">
#using (Html.BeginForm("SearchSpots", "Spots", FormMethod.Post))
{
#Html.AntiForgeryToken()
<input id="searchfilter" type="text" class="form-control" autocomplete="off" placeholder="Search" name="searchfilter">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
}
</div>
</div>
</div>
And you can add [ValidateAntiForgeryToken] in your action
This is a routing issue. You don't have a route that will hit SearchSpots with a parameter. So either change your route, or change the BeginForm to include the parameter.
ASP.NET MVC - passing parameters to the controller
Pass multiple parameters in Html.BeginForm MVC

asp.net mvc client side validation not working?

For some reason my client side validation does not seem to be working:
Here is my html:
#using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
<hr />
#Html.ValidationSummary(true)
<hr />
<p>
<label>Select Client_ID: </label>
<span class="field">
<select name="clientId" id="clientId">
#foreach (var item in Model.ClientId)
{
<option value="#item">#item</option>
}
</select>
</span>
</p>
<p>
<label>#Html.LabelFor(model => model.UserModel.name)</label>
<span class="field">
#Html.EditorFor(model => model.UserModel.name)
</span>
#Html.ValidationMessageFor(model => model.UserModel.name)
</p>
<p>
<label>#Html.LabelFor(model => model.UserModel.password)</label>
<span class="field">
#*<input name="password" id="password" type="password" />*#
#Html.EditorFor(model => model.UserModel.password)
</span>
#Html.ValidationMessageFor(model => model.UserModel.password)
</p>
<p>
<label>#Html.LabelFor(model => model.UserModel.email)</label>
<span class="field">
#*<input name="email" id="email" type="email" />*#
#Html.EditorFor(model => model.UserModel.email)
</span>
#Html.ValidationMessageFor(model => model.UserModel.email)
</p>
<p>
<label>Select: </label>
<span class="field">
<select name="accessLevel" id="accessLevel">
<option value="3">Company</option>
<option value="5">End-User</option>
</select>
</span>
</p>
<input type="submit" value="Submit" />
Here is my model:
public class CreateUserModel
{
[Required]
[Display(Name = "Client_ID")]
public string clientId { get; set; }
[Required(ErrorMessage = "A name is required")]
[MaxLength(20), MinLength(2, ErrorMessage = "Name must be 2 character or more")]
[Display(Name = "Name")]
public string name { get; set; }
[Display(Name = "Email Address")]
[Required(ErrorMessage = "Email is Required")]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}" +
#"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
#".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
ErrorMessage = "Email is not valid")]
public string email { get; set; }
[Required]
[MaxLength(20), MinLength(6, ErrorMessage = "Password Must be 6 or more chataters long")]
[Display(Name = "Password")]
public string password { get; set; }
[Required]
public int accessLevel { get; set; }
}
and I do have client side enabled in the webconfig:
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
{EDIT} added rendered html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page - My ASP.NET Application</title>
<link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>
<script src="/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
<script src="/Scripts/jquery.validate.js"></script>
<div class="jumbotron">
<h1>Add Users to the website</h1>
</div>
<form action="/Home/Create" method="post"> <hr />
<hr />
<p>
<label for="UserModel_name">Name</label>
<span class="field">
<input type="text" name="name" />
</span>
<span class="field-validation-valid" data-valmsg-for="UserModel.name" data-valmsg-replace="true"></span>
</p>
<p>
<label for="UserModel_password">Password</label>
<span class="field">
<input name="password" id="password" type="password" />
</span>
<span class="field-validation-valid" data-valmsg-for="UserModel.password" data-valmsg-replace="true"></span>
</p>
<p>
<label for="UserModel_email">Email Address</label>
<span class="field">
<input name="email" id="email" type="email" />
</span>
<span class="field-validation-valid" data-valmsg-for="UserModel.email" data-valmsg-replace="true"></span>
</p>
<p>
<label>Select: </label>
<span class="field">
<select name="accessLevel" id="accessLevel">
<option value="3">Company</option>
<option value="5">End-User</option>
</select>
</span>
</p>
<input type="submit" value="Submit" />
</form>
<hr />
<footer>
<p>© 2014 - My ASP.NET Application</p>
</footer>
</div>
<script src="/Scripts/jquery-2.1.0.js"></script>
<script src="/Scripts/bootstrap.js"></script>
For some reason the Html helpers does not have generated validation attributes in the inputs (data-val="true" and the others), check that. Besides to check the order in which the javascript libraries are loaded:
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/jquery.validation.js"></script>
<script src="~/Scripts/jquery.validation.unobtrusive.js"></script>
Your problem is likely that you have jQuery at the bottom of your file, but you are putting jquery.validate at the top. jQuery has to come before jQuery.validate. I would suggest always putting jQuery in your header, not in the body, and it should be the first thing after modernizr.
Also, you do know that jQuery 2.x does not work with IE8 ore earlier, right?
It seems that your jquery.validate.js is in wrong position. It must be after main jquery ref.
For MVC 5, it should be as following:
_Layout.cshtml: (bottom of page)
<body>
...
...
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/jqueryval") <!-- *required for client side validation! -->
#RenderSection("scripts", required: false)
</body>
where ~/bundles/jqueryval is defined in BundleConfig.cs: RegisterBundles() method:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
Use:
#Html.EditorFor
Instead of:
<input>
And of course you need the jquery.validate.* scripts
TRY THIS: Your validation is failing because you have hard-coded this JQuery link version at the bottom of your page, which likely has been updated to a newer version in your Scripts folder:
<script src="/Scripts/jquery-2.1.0.js"></script>
All you need to do is go to "Scripts", see if there is a "jquery-2.1.0.js" file or you updated JQuery to a newer version. Type in the newer version file name, if found, and retest. It should work now. As of this June 2017 we are on JQuery version 3.1.1
This happened to me and I was pulling my hair out till I realized I had updated JQuery and saw it removed the old version. I bet that's your issue. In case you are not doing this, I recommend you not follow the View Page templates that stick validation scripts in View Pages and instead create a simple usercontrol or masterpage or layout view page and stuff your JQuery links in there so they are shared universally by all project pages. The browser will naturally cache these pages the first time, so even if they aren't used on other pages they are not loaded again.
Not sure if this is being loaded dynamically (e.g loading a partial view with Ajax). If so then you need to parse the html with the validator on the success e.g.
Use something like...
$.validator.unobtrusive.parse(".target");
E.g.
function loadAPartialView(endPoint) {
$.ajax({
url: endPoint,
type: 'GET',
cache: false,
success: function (result) {
$('.target').html(result);
$('.target').show();
// IMPORTANT. Next line is required to get the client side validation to run.
$.validator.unobtrusive.parse(".target");
$(".loadingMessage").hide();
},
error: function (result) {
// Error message...
$(".loadingMessage").hide();
}
});
};

.net Html.RenderAction returns binary instead of HTML. Huh?

I'm not sure exactly what I'm doing wrong here.
I have an action which returns a partial view:
public class SharedController : BaseController
{
public ActionResult StudentPoll()
{
WAM.X2O.FuelUpToPlayContext db = new WAM.X2O.FuelUpToPlayContext(WAM.Utilities.Config.ConnectionString);
WAM.X2O.StudentPoll m = (from s in db.StudentPolls where s.IsActive == true select s).SingleOrDefault();
return PartialView("StudentPoll", m);
}
}
I implement the action like this:
<%Html.RenderAction("StudentPoll", "Shared");%>
The partial view looks like this:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl< Fuel_Up_To_Play.Models.Shared.StudentPollModel >" %>
<%if(ViewData.Model != null){ %>
<div class="block">
<div class="holder">
<div class="frame">
<h2 class="poll">Student Poll</h2>
<!-- TODO - Student Poll has a form screen, and results screen.
Results anim is here to demo what should happen after submision -->
<form action="/Shared/SubmitStudentPoll" method="post" class="poll-form" <%if(ViewData.Model.StartingState == Fuel_Up_To_Play.Models.Shared.StudentPollModel.PollStates.RESULTS){%>style="display:none"<%} %>>
<fieldset>
<span><%=ViewData.Model.StudentPoll.Question %></span>
<input type="hidden" id="student_poll" name="student_poll" value="<%=ViewData.Model.StudentPoll.ID %>" />
<%foreach(WAM.X2O.StudentPollAnswer answer in ViewData.Model.StudentPoll.RelatedStudentPollAnswers){ %>
<div class="row">
<input type="radio" class="radio" id="answer_<%=answer.ID %>" name="poll_answer" value="<%=answer.ID %>"/>
<label for="answer_<%=answer.ID %>"><%=answer.AnswerText%></label>
</div>
<%} %>
<input id="submitBtn" type="image" style="display:none" class="image" src="/Content/images/btn-submit-05.gif" />
</fieldset>
</form>
<div class="progress-box" <%if(ViewData.Model.StartingState == Fuel_Up_To_Play.Models.Shared.StudentPollModel.PollStates.FORM){%>style="display:none"<%} %>>
<span><%=ViewData.Model.StudentPoll.Question %></span>
<%int answerCounter = 0;
foreach(WAM.X2O.StudentPollAnswer answer in ViewData.Model.StudentPoll.RelatedStudentPollAnswers){ %>
<div class="box">
<span class="names"><%=answer.AnswerText%><strong class="quesPctTxt" rel="<%=ViewData.Model.AnswerPercentages[answerCounter] %>"></strong></span>
<div class="progress-bar"><span class="quesPctBar"></span></div>
</div>
<%
answerCounter++;
} %>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="/Scripts/studentpollscript.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("input.radio[name='poll_answer']").change(function() {
$("#submitBtn").show();
});
$("#submitBtn").click(function() {
$(".poll-form").ajaxForm(
{ dataType: 'json',
success: function(json) {
alert(json.Success);
}
}
);
});
});
</script>
<%} %>
Natually, I would expect this approach to return HTML. But no. Instead it appears that binary is being rendered in the browser. Obviously I'm doing something wrong but I don't know what.
Here's what is rendered in the browser:
http://screencast.com/t/Mjg1OWJj
Any ideas folks? I'm stumped but I'm sure it's something simple that I'm missing.
I would guess that it simply isn't setting the content type correctly. What does a network trace (fiddler, etc) show? Perhaps try using View("StudentPoll", m); instead of PartialView(...)?
Also; be careful - many of those <%= look unsafe, i.e. not html-encoded.

Categories

Resources