Prevent page refresh on submit button click - asp.net-mvc-4

I am working in Mvc4. Creating a validation. When I am clicking the submit button and the validation is getting failed and the full page is getting refreshed to display the validation messages. I do not want my page to get refreshed. And another question is is there any way to do the model validation without Httppost?

In the server-side validation ,the page must be submitted via a postback to be validated on the server and if the model data is not valid then the server sends a response back to the client. With client-side validation, the input data is checked as soon as they are submitted, so there is no postback to the server and there is no page refresh.
By Using the Code you can add client side validation.
Please add following app setting code snippet in the web.config file.
<configuration>
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
</configuration>
Please add below scripts in your view.
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
Please try with above code and let me know if any concern. Please check below demo link for more detail.
Link1
Link2

Related

Handling exceptions before startup

I have an application that can throw an InvalidOperationException during the startup process before the host has been created. What I would like to do is capture this error, and handle it by displaying a static, custom error page (i.e. ErrorPage.html)
Is this possible? Everywhere I seem to look makes it seem as though this is an impossible task and that the default 500.30 - ASP.NET Core app failed to start is the only page that will appear in a situation where the host fails to establish by the time the exception is thrown.
One option to achieve a custom error page on host errors generating 500 responses would be to use some gateway or proxy in front of your app. The idea would be to handle certain responses by showing some error content from the gateway.
Options would include custom error pages in Azure Application Gateway or a middleware handler if using a YARP proxy instance.
For IIS use web.config and add a section inside element <system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<error statusCode="500" subStatusCode="30" path="ErrorPage.html" responseMode="File" />
</httpErrors>
Check docs for more information

BetterCMS with MVC4 Simple membership provider

I've set up BetterCMS in my MVC4 app. and it seems like it's working except I can't figure out how to configure it to use Simple Membership Provider that comes with MVC4 internet app.
http://www.devbridge.com/articles/better-cms-for-developers
please help!. thanks
EDIT: I've created my MVC4 app using Internet Template which comes with Simple Membership Provider already configured and working. I would like to have those members I've "registered" as BetterCMS users.
If you want to use Better CMS, use BetterCms.Module.Users module from NuGet with it's role provider, membership provider and UI for managing users. How to setup users module, you can read in BetterCMS wiki pages on Github
But if you still wish to use Better CMS with Simple Membership Provider, follow steps below. That's what I've done and it works fine for me.
Create an MVC 4 solution and select Internet template
Run the application and create a user
Install BetterCMS by following steps, explained in Better CMS github wiki, section "Project Setup".
Do not forget to remove default routes registration (routes.MapRoute(name: "Default" ....) from RouteConfig class.
Register routes below in the RouteConfig class. After that MVC home page can be reached by URL /home/:
routes.MapRoute("mvc-account-controller", "account/{action}/{id}", new
{
area = string.Empty,
controller = "Account",
action = "Login",
id = UrlParameter.Optional
});
routes.MapRoute("mvc-home-controller", "home/{action}/{id}", new
{
area = string.Empty,
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
Add role provider and membership provider to web.config (solution found here):
<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>
Add LazyInitializer to global.asax as explained here
Remove [InitializeSimpleMembership] attribute from AccountController, because database connection is already initialized. Also, SMP2.Filters.InitializeSimpleMembershipAttribute class can also be deleted.
Create an admin role and assign it for user (it can be done using ASP.NET Configuration or directly in the database). For example, create role with name "Role1".
There are two ways to set up administrator roles for the user (you can read more in the Better CMS Github Wiki, topic "CMS configuration"):
Set your created role as full access role (cms.config, security section's fullAccessRoles attribute set to fullAccessRoles="Role1" )
Add roles mappings in the cms.config's security section:
<customRoles>
<add permission="BcmsEditContent" roles="Role1" />
<add permission="BcmsPublishContent" roles="Role1" />
<add permission="BcmsDeleteContent" roles="Role1" />
<add permission="BcmsAdministration" roles="Role1" />
</customRoles>
Run application. Go to url /account/login and log-in using admininstrator account, which was created in the 2nd step. Then go back to any CMS page, for example, root page (/).
Here you go, you're connected as administrator and CMS sidebar is availabe for web site editing.

How to extend a user's session in MVC 4 forms authentication via AJAX

I'm using Forms Authentication for an internal company website. I authenticate users against the local Active Directory server.
I have my Web.config file set up as follows:
<authentication mode="Forms">
<forms name=".ADAuthCookie" loginUrl="~/Login" timeout="30" slidingExpiration="true" protection="All" defaultUrl="/" />
</authentication>
This works fine as long as a user moves to a new page, or refreshes the page they're on. However, much of my UI is based on javascript templating and AJAX, so it's quite possible for a user to be working on a page for longer than 30 minutes.
So, how do I query and/or extend how much time they have remaining in their session via an AJAX call? I don't need help with the AJAX call, just what I'd put in a controller (such as /user/keepalive)

potentially dangerous Request servicestack

I am submitting a query string that contains a value
Body=%3Ch2%3E (Body=<h1>)
to a servicestack rest endpoint. That results in:
A potentially dangerous Request.QueryString value was detected from the client (Body=\"<h2>\").
I know that in MVC 4 you can allow Html content for an specific field, if you decorate the field in the model with [AllowHtml] like so:
[AllowHtml]
public string Body { get; set; }
Did that, but the error persists. Had doubts that it was service stack not partaking properly in the validation process, so tested by creating a pure MVC 4 controller with the same model, and that works fine.
However I need a solution for ServiceStack. Their documentation is thin and Google searches lead nowhere.
It looks like you are hosting your ServiceStack service inside an ASP.NET application.
You could add the following to the <system.web> section of your web.config file in order to disable request validation for the entire application:
<system.web>
<httpRuntime requestValidationMode="2.0" />
...
</system.web>
And if you want to disable request validation only for a particular endpoint and not the entire application use the <location> tag in your web.config:
<location path="hello">
<system.web>
<httpRuntime requestValidationMode="2.0" />
</system.web>
</location>
This will disable request validation for all /hello endpoints in your application. For example /hello?Body=%3Ch2%3E will work but /bar?Body=%3Ch2%3E won't work.
You can read more about request validation in ASP.NET in the following MSDN article.
And obviously you should not be worried about this if you are self-hosting your ServiceStack service.

Authentication causing duplicate page rendering

Let me try to explain this in english :).
I'm having trouble with the authentication in Mvc. I use my layout page to login and to show the other partial views with content.
I decorated the login methods with <AllowAnonymous()> _ to let people login into the page and in my webConfig i have the following entry:
<authentication mode="Forms">
<forms loginUrl="~/" timeout="2880" />
</authentication>
What's happening is when the session expires, the partial view renders the entire page again and i get the entire page twice (one inside the content).
Any help?
You may checkout the following article from Phil Haack which illustrates a nice technique allowing you to prevent the forms authentication module to automatically redirect to the LogOn page but return 401 status code. This could be done conditionally only for AJAX requests. And since the server now returns 401 status code you could detect it on your client side AJAX call and act accordingly.
Thks for the answer, but i solved my problem with the following post :
C# MVC: How to override configured authentication redirect?