I am using remote validator but it's not working even debugger isn't tracing that method.
public JsonResult CheckStrategyName(string StrategyName)
{
var ab = from a in db.Sterategy where a.StrategyName == StrategyName select a.StrategyName;
return !ab.Any() ? Json(true, JsonRequestBehavior.AllowGet) : Json(string.Format("Name Already esists"), JsonRequestBehavior.AllowGet);
}
I have used it here
[Required]
[Remote("CheckStrategyName", "St", ErrorMessage = "Already exists ")]
[Display(Name = "Name")]
public string StrategyName { get; set; }
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" />
</appSettings>
Where am I making mistake ? :(
Your server code & settings seems to be fine. Make sure the following are in place
You are using the TextBoxFor helper method to generate the relevant input field markup and it is inside a form.
#using (Html.BeginForm())
{
#Html.TextBoxFor(s => s.StrategyName)
#Html.ValidationMessageFor(s => s.StrategyName)
<input type="submit" value="Submit" />
}
You have included the javascript libraries needed for validation.
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
Related
I am trying to upload an mp4 video file that is 5.25 MB in size in an ASP.NET MVC 5 application.
I have tried adding this to the Web.config file which has been the accepted answer in most cases to this problem.
<system.web>
<!-- This will handle requests up to 1024MB (1GB) -->
<httpRuntime maxRequestLength="1048576" />
</system.web>
I've also tried setting the timeout as well in the Web.config
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
However, when I go to upload the file I am getting System.Web.HttpException (0x80004005): Maximum request length exceeded.
Maybe there is something that needs to be set in the controller or view?
Controller:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
if (fileName != null)
{
var path = Path.Combine(Server.MapPath("~/Content/Videos"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}
View:
#using (Html.BeginForm("Edit", "Posts", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
How do you upload video files in ASP.NET MVC 5?
Try add this in web.config (in bytes !):
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
I'm trying to implement a single-page app. I carried over some of my working code from another project (MVC4) to implement authentication. Right now I see cookies being set, but WebSecurity / User.Identity do not seem to be working for some reason. After logging in, subsequent requests never validate as authenticated, either via WebSecurity.IsAuthenticated, or User.Identity.IsAuthenticated. Does anyone know why this is happening?
Controller code:
public class AccountController : ApiController {
private readonly UserService _userService;
public AccountController() {}
public AccountController(UserService userService) {
_userService = userService;
}
[AllowAnonymous]
[HttpGet]
[Route("api/authpayload")]
// This gets called when the app loads. Always, User.Identity.IsAuthenticated is false.
public HttpResponseMessage AuthPayload() {
var payload = new AuthPayloadDto();
try {
var userId = WebSecurity.GetUserId(User.Identity.Name);
if (User.Identity.IsAuthenticated && userId > 0) {
payload.Username = User.Identity.Name;
} else {
LogOut();
payload.IsAuthenticated = false;
}
return Request.CreateResponse(HttpStatusCode.OK, payload);
} catch (Exception e) {
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
[HttpPost]
[Route("api/login")]
[AllowAnonymous]
public HttpResponseMessage LogIn(LoginModel model) {
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
try {
if (WebSecurity.IsAuthenticated)
return Request.CreateResponse(HttpStatusCode.Conflict, "already logged in.");
if (!WebSecurity.UserExists(model.Username))
return Request.CreateResponse(HttpStatusCode.Conflict, "User does not exist.");
if (WebSecurity.Login(model.Username, model.Password, persistCookie: model.RememberMe)) {
// This code always gets hit when I log in, no problems. I see a new cookie get sent down as well, using Chrome debugger.
var payload = new AuthPayloadDto();
return Request.CreateResponse(HttpStatusCode.OK, payload);
}
LogOut();
return Request.CreateResponse(HttpStatusCode.Forbidden, "Login Failed.");
} catch (Exception e) {
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
Web.config:
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/" timeout="2880" />
</authentication>
<roleManager enabled="true" defaultProvider="simple">
<providers>
<clear />
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="simple">
<providers>
<clear />
<add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<!--
If you are deploying to a cloud environment that has multiple web server instances,
you should change session state mode from "InProc" to "Custom". In addition,
change the connection string named "DefaultConnection" to connect to an instance
of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express.
-->
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
</system.web>
The cookie that gets sent after login is not expired, and it does get sent back on subsequent requests, but IsAuthenticated is always false. What am I doing wrong?
Update:
I updated my web.config to the following to get everything working:
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear />
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
</system.web>
But I'd like to leave this open in case anyone has an explanation of why this works; I'm pretty lost.
In my current mvc 4 project with mssql,
its a simple one i so I just wanted very simple memmbership provider
I disabled
InitializeSimpleMembershipAttribute
by
[Authorize]
//[InitializeSimpleMembership]
public partial class AccountController : Controller
and added this code to global.asax under Application_Start
WebSecurity.InitializeDatabaseConnection(
connectionStringName: "DefaultConnection",
userTableName: "UserProfile",
userIdColumn: "UserID",
userNameColumn: "UserName",
autoCreateTables: true);
in my sql database the application created some tables on of them was Roles and UserInRoles just added the roles I needed like Admin, customer, etc...
and I restrict the access to some Controllers or Actions by adding this code
[Authorize(Roles = "Admin")]
public class MessagesController : Controller
I have an issue on custom html helper method. I have added two custom html helper method. First method is MyTextBox and second one is MySelectBox Method which is extention to the HtmlHelper class.The following code is working fine.
C# :
namespace MyHtmlHelper
{
public static class HtmlHelperClass
{
public static MvcHtmlString MyTextBox(string fieldName)
{
return new MvcHtmlString("<input type=\"text\" name=\"" + fieldName + "\"></input>");
}
}
}
namespace MyHtmlHelper
{
public static class HtmlHelperExtension
{
public static MvcHtmlString MySelectBox(this HtmlHelper helper, string text)
{
return new MvcHtmlString("<select ><option>" + text + "</option></select>");
}
}
}
view:
#using MyHtmlHelper
<div>
#MyHtmlHelper.HtmlHelperClass.MyTextBox("test")
#Html.MySelectBox("Test")
</div>
I want this html helper method for all views in my application.so i removed MyHtmlHelper namespace from view and added in web.cong as follows
Web.config :
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
<add namespace="MyHtmlHelper"/>
</namespaces>
</pages>
My Problem is : MyTextBox helper method working fine but html extension method (MySelectBox) is not working.Anyone please help me ,what mistake i have done or how to resolve this issue?
There is a another webconfig in the view folder. You have to use this.
I am working on an app using the ASP.NET membership provider. By default, i can use a few fields such as username, password. How to add to the asp.net membership provider so I can add Profile fields such as "firstName", "lastName" in the register section and have it save to the database in aspnet_profile table along with other data.
I am creating a user in the account model as below:
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password,
model.Email,model.PasswordQuestion,model.PasswordAnswer,
true, null,out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
return View(model);
}
Now which function i should use to store profile info into db?
Help me !!
Add the fields to the profile section of Web.Config.
<profile>
<properties>
<add name="FirstName" />
<add name="LastName" />
<add name="Address1" />
<add name="Address2" />
<add name="City" />
<add name="State" />
<add name="Zip" />
<add name="Phone" />
<add name="ProfileVersion" type="int" defaultValue="0" />
</properties>
</profile>
For more information please visit: http://msdn.microsoft.com/en-us/magazine/cc163457.aspx
I am trying to get remote validation working in ASP.NET MVC 3 but for some reason the validation never gets fired. I am returning json from the controller and in FireFox it ask me to download the files. Not sure what is going on here. Here is my code:
#using(Html.BeginForm(new {Action = "ValidateUserName"})) {
<text> Enter UserName: </text> #Html.TextBoxFor(x => x.UserName)
<input type="submit" value="Login" />
}
Here is the RegistrationViewModel:
public class RegistrationViewModel
{
[Required(ErrorMessage = "UserName is required!")]
[Remote("ValidateUserName","Home",ErrorMessage ="UserName already taken!")]
public string UserName { get; set; }
}
And here is the HomeController:
public ActionResult ValidateUserName(RegistrationViewModel registrationViewModel)
{
return Json(!registrationViewModel.UserName.Equals("test"),JsonRequestBehavior.AllowGet);
}
A couple of things to consider:
1) In your view, you should be referencing the jquery validation and unobtrusive javascript libraries:
<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>
2) Also in your view, you should have an Html.ValidationMessageFor(m => m.Attribute):
#Html.ValidationMessageFor(x => x.UserName)
3) Lastly, make sure you have the two AppSettings in your web.config file that enable the client-side validation.
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>