Menu
  • HOME
  • TAGS

ASP.NET MVC Remove Model Validations

Tag: asp.net-mvc,validation,form-submit

Let's suppose I have a form with two submit buttons: save and delete.

How can I remove/disable model validations on delete button?

Best How To :

Assuming you're using standard unobtrusive/jQuery validate; Disable client-side validation by putting a class of "cancel" on the button:

<button type="submit" class="cancel">Delete</button>

This will prevent client-side validation from firing at all in the event of this button being clicked.

For server side, just don't check if the model's valid or not.

ASP.NET httpHandlers & handlers

asp.net,asp.net-mvc

The system.webServer section in the Web.config file specifies settings for IIS 7.0 that are applied to the Web application. The system.WebServer is a child of the configuration section. For more information, see IIS 7.0: system.webServer Section Group (IIS Settings Schema). and <system.web> specifies the root element for the ASP.NET configuration...

ASP.NET MVC posting list from view to controller

c#,.net,asp.net-mvc,razor

That's probably a good candidate for an EditorTemplate to be honest, that way you don't have any issues with prefixing: @Html.EditorFor(m => m.TechnologyFilters) Without using an editor template though, a technique you can use is to specify the prefix in your partial declaration within the ViewDataDictionary, by doing: Html.RenderPartial("_TechnologyFilters", Model.TechnologyFilters,...

When adding a user to a role in asp.net mvc 4.5, i'm getting an error- “user (user name) not found”

c#,asp.net-mvc

The problem is you are not setting roleManager properly in webconfig. change your webconfig as below. <roleManager enabled="true" cacheRolesInCookie="true" cookieName=".ASPXROLES" cookieTimeout="30" cookiePath="/" cookieRequireSSL="false" cookieSlidingExpiration="true" cookieProtection="All" defaultProvider="AspNetSqlRoleProvider" createPersistentCookie="false" maxCachedResults="25" /> ...

Show/hide tinymce with radio buttons

c#,asp.net,asp.net-mvc,tinymce

Your missing an @symbol for the id attribute: Modify your script as well like this: ***EDIT some thing seems off about the radio buttons only one should be checked and they should have the same name ** you can use the # to denote and ID in Jquery by the...

Javascript/jQuery form validation

javascript,jquery,forms,validation

Add an onchange event to your text inputs that will remove the error message. Rather than making a count of valid fields, I would also check for the existence of error messages. This will make it easier to add more fields to your form. function checkName(e) { //gather the calling...

C# Validate DataSet filled with DGV data as XML

c#,xml,validation,datagridview,xsd

If the question is why can't the file be deleted, it is because the XmlReader has the file open - call read.Close() before trying to delete the file.

HTTP Error 403.14

asp.net-mvc,visual-studio-2013

Stilly! There is a refactor bug in VS that changes the routes as well! My default route was changed to the following and I had to rename name to id and everything is working fine! routes.MapRoute( name: "Default", url: "{controller}/{action}/{name}", defaults: new { controller = "Home", action = "Index", id...

Creating a viewmodel on an existing project

c#,asp.net,asp.net-mvc

You are using a namespace, your full type name is Project.ViewModel.ViewModel (namespace is Project.ViewModel and class name is ViewModel) so use this using instead: @model Project.ViewModel.ViewModel ...

How to map between two entities before paging

c#,asp.net-mvc,entity-framework

You just want to make sure you don't pull anymore records out of the database than you need. As you can't use your ProviderViewModel constructor in LINQ to Entities you will have to retrieve the requested page yourself before creating your view model objects: public ActionResult Index(int? page) { List<ProviderViewModel>...

.NET MVC: Finding default Bootsrap JavaScripts

javascript,asp.net-mvc,twitter-bootstrap

You can reference the open li using css class selector '.': $(".dropdown.open") this will give you the currently open dropdown. Explanation: 'CSS selectors' allow you to select elements using CSS syntax. For example: '#id' where the '#' indicates the following text is the id of the element. '.class' allows you...

Checkbox to be checked on having value Y

asp.net-mvc,knockout.js

Use a computed writable observable: var ViewModel = function() { var self = this; self.actualObservable = ko.observable('Y'); self.relatedObservable = ko.computed({ read: function() { return self.actualObservable() === 'Y'; }, write: function(x) { self.actualObservable(!!x ? 'Y' : 'N'); } }); }; ko.applyBindings(new ViewModel()); <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <input type="checkbox" data-bind="checked: relatedObservable"> = Checked<br />...

Avoid EF update the null image to database in .Net MVC

asp.net-mvc,entity-framework,null,edit,httppostedfilebase

Mark Image property as not modified: db.Entry(sach).State = EntityState.Modified; if (image == null) db.Entry(sach).Property(m => m.Image).IsModified = false; db.SaveChanges(); ...

How to use ajax to post json string to controller method?

jquery,asp.net-mvc,visual-studio-2013,asp.net-mvc-5

Your action method is expecting a string. Create a javascript object, give it the property "data" and stringify your data object to send along. Updated code: $.ajax({ type: 'post', dataType: 'json', url: 'approot\Test', data: { "json": JSON.stringify(data) }, success: function (json) { if (json) { alert('ok'); } else { alert('failed');...

How to hide columns in Kendo Grid when editing in a popup

asp.net-mvc,kendo-ui,kendo-grid,kendo-asp.net-mvc

You can use the edit event of the grid to hide some element from the popup window: $("#grid").kendoGrid({ edit: function(e) { e.container.find(".k-edit-label:first").hide(); e.container.find(".k-edit-field:first").hide(); } }); ...

Can I check if action is a child action in a view?

c#,asp.net-mvc,razor

You can use ViewContext.IsChildAction in view.

How to Convert a Time to local Time in Different TimeZone

c#,asp.net,asp.net-mvc,timezone,timezoneoffset

The main problem I see with your code is the first line in your TimeAgo() method: The DateTime dt object you pass to this method is local time for your clients, but then you use the server local time DateTime.Now to calculate the timespan. Pass the UTC timestamps you get...

how to multiply two column names using codeigniter validation rule

php,codeigniter,validation

You done need to do anything with your controller. Add this change your view to <script> function calculate() { var myBox1 = document.getElementById('crop_quantity').value; var myBox2 = document.getElementById('per_rate').value; var result = document.getElementById('income_amount'); var myResult = myBox1 * myBox2; result.value = myResult; } window.onload = calculate(); </script> <div class="control-group"> <label class="control-label">Crop Quantity</label>...

Validation of a form before submission

php,validation,symfony2,form-submit

In place of: $form->submit($request->request->get($form->getName())); Try: $form->submit(array(), false); ...

Best approach to upgrade MVC3 web app to MVC5?

c#,.net,asp.net-mvc,asp.net-mvc-5

There's a handy documented guide by Rick Anderson which he wrote to upgrade from MVC4, the same applies to you with the exception of the fact that the "Old version" of DLLs he mentions will be different to the ones that you will have, but the outcome will still be...

Url.Action Compilation Error : BC30988: Type or 'With' expected

javascript,c#,html,asp.net-mvc

Why are you doing it that way,you can sort it by using Url.Action() and concatenating query string parameters this way: function patrListClick(PAT_ID) { window.location.href = '<%: Url.Action("PatrList", "Patr") %>?id='+PAT_ID; } ...

ViewData Compilation Error : BC30203: Identifier expected

javascript,c#,jquery,html,asp.net-mvc

Add below line to top of the view page, then it works perfect. <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> ...

How to format label in ASP.net chart control

c#,asp.net,asp.net-mvc,c#-4.0,reporting-services

Use formatting: DateTime.Now.ToString("dddd, dd-MM-yy"); Output: Montag, 15-06-15 //Written day of week in your local culture. To edit the axis labeling, you can do it in your code-behind file: Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "dddd, dd-MM-yy"; Or in your markup: <ChartAreas> <asp:ChartArea Name="ChartArea1"> <AxisX Title="Date" IsLabelAutoFit="True" TitleForeColor="#ff0000"> <LabelStyle Format="dddd, dd-MM-yy" /> <MajorGrid Enabled ="False"...

Angularjs resource with scope parameter

javascript,asp.net-mvc,angularjs,single-page-application

If this is an AJAX call then the varialble initialization should be into the callback methods: Fakturi.fakturi.get({ id: $routeParams.id }, function (data) { $scope.faktura = data; }); Fakturi.komintenti.get({ id: $scope.faktura.KomintentID }, function (data) { $scope.komintent = data; }); According to this link, if you would like to get response immediately...

Adding where clause to IEnumerable Select

c#,asp.net-mvc,linq

Per Discosultan in the comments: IEnumerable<int> interestIds = viewModel.ExistingInterests.Where(x => x.selected == true).Select(x => x.InterestId); ...

devenv.exe hogs CPU when debugging

asp.net-mvc,visual-studio-2013

I didn't manage to find the source of the problem, but closing all editor windows in VS seems to make it go away. If there are further lag spikes, restarting debugging might be also a good idea. Since I didn't see this problem in a new project, it might be...

which approach is best for GET,POST using Rest API [closed]

c#,jquery,asp.net-mvc,angularjs

There is no 'best' way to do this, but I'd suggest implementing your RESTful API using ASP.NET Web API and then consuming that with AngularJS on the front-end (using the $http service). It's a pretty neat way of communicating with your APIs without having to navigate away from the page,...

How to validate non-db attributes on an ActiveRecord model?

ruby-on-rails,validation,activerecord

You can use =~ operator instead to match a string with regex, using this you can add a condition in setter methods def resolution=(res) if res =~ /\A\d+x{1}\d+\d/ # do something else # errors.add(...) end end but, as you have already used attr_accessor, you don't have to define getter and...

How to use Autofac to inject specific implementation in constructor

c#,asp.net-mvc,dependency-injection,autofac

Autofac is nicely documented and it looks like you can find what you are after here. From what I can tell, if you have registered your updators with builder.RegisterType<LastActivityUpdator>(); builder.RegisterType<AnonymousUserLastActivityUpdator>(); then you should be able to register your services with builder.Register(c => new UserService(c.Resolve<LastActivityUpdator>())); builder.Register(c => new AnonymousUserService(c.Resolve<AnonymousUserLastActivityUpdator>())); or...

Database object with different data

sql,asp.net,asp.net-mvc,database,entity-framework-6

Ideally what you want is a many-to-many relationship between your Shop and Product entities: public class Shop { public int ShopId {get; set;} public virtual ICollection<ShopProduct> ShopProducts {get; set;} } public class Product { public int ProductId {get; set;} public string Name {get; set;} public virtual ICollection<ShopProduct> ShopProducts {get; set;}...

ASP.NET MVC Client side time convert from model

javascript,asp.net-mvc,model

I don't think you can achieve this without using JavaScript. Here's something you could try (using jQuery for convenience): foreach (var item in Model) { <tr> <td data-iso="@item.someDate.ToString("o")"></td> </tr> } Afterwards, in document.ready just parse the date and set the locale in the td: $("document").ready(function () { $("td").each(function (index, elem)...

Dynamically adding controls in MVC4

asp.net-mvc,asp.net-mvc-4

You can create a editor template and pass the control list as model to the template and in the template you can iterate that list to generate the control. As i have shown below. 1->Create a class for Control Information. public class ControlInfo { public string ControlType { get; set;...

Why is my View not displaying value of ViewBag?

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor

ViewBag is used when returning a view, not when redirecting to another action. Basically it doesn't persist across separate requests. Try using TempData instead: TempData["Tag"] = post.SelectedTag.ToString(); and in the view: <p><strong>Tag: @TempData["Tag"]</strong></p> ...

Multiple Posted Types asp.net 5 MVC 6 API

c#,asp.net,asp.net-mvc,asp.net-5,asp.net-mvc-6

The best way is to create a composite wrapper: public class Wrapper { public ModelA A { get; set; } public ModelB B { get; set; } } Put Wrapper in the parameter list and mark that [FromBody]. You can't use that attribute more than once because all of the...

Codeigniter Form Validation Rule for match (password)

php,forms,codeigniter,validation

There is no need of putting old password has in hidden field. it's not even safe. you can create callback function for your own custom validation. Notice the comment i have did in following code. $config=array( array( 'field' => 'old_password', 'label' => 'oldpass', 'rules' => 'trim|required|callback_oldpassword_check' // Note: Notice added...

Output Raw String in ASP.NET MVC Razor [duplicate]

c#,asp.net-mvc,razor

You can use Html.Raw to output the unencoded data: <input id='myHiddenInput' type='hidden' value='@Html.Raw(ViewBag.Text)' /> Here is a link to dotnetfiddle. You can see the output in text field, but there is also a hidden field with the same unencoded information....

How to enable multiple login tries in asp.net forms authentication?

c#,asp.net,asp.net-mvc,authentication

It's because of your ViewBag's returnUrl sets null after postback, just simply put ViewBag.ReturnUrl = returnUrl; at the beginning of your HttpPost verb of Login action. ...

jQuery validate equalTo

javascript,jquery,validation

I have done a quick hack to solve this. It works well although this may not be the preferred way to do it. Add a hidden input #fullname Populate the hidden input with the value of first and last name separated by a space Validate the signature agianst the hidden...

MVC route attribute no controller

asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing

Ok so ranquild's comment pushed me in the right direction. In my route config, I had the default route of routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); So that my homepage would still work on the url with...

File IO Close() method error in ASP.NET MVC 6

asp.net-mvc,asp.net-mvc-6

Do you use the core CLR? The StreamWriter.Close method are not available in core CLR. You can use Dispose method replace. You also can use using statement: using (var writer = System.IO.File.CreateText("your_path")) { writer.WriteLine("text"); } ...

Correct PHP contact form syntax? [duplicate]

php,forms,validation

The first time you load the form, $_POST will not have anything populated. Try changing if ($_POST["submit"]) { to if (isset($_POST["submit"])) { to determine if the form was in fact submitted and continue accordingly....

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?

asp.net-mvc,asp.net-mvc-4,razor,asp.net-mvc-5,claims-based-identity

Your claim identity does not have ClaimTypes.NameIdentifier, you should add more into claim array: var claims = new List<Claim> { new Claim(ClaimTypes.Name, "Brock"), new Claim(ClaimTypes.Email, "[email protected]"), new Claim(ClaimTypes.NameIdentifier, "userId"), //should be userid }; To map the information to Claim for more corrective: ClaimTypes.Name => map to username ClaimTypes.NameIdentifier => map...

check if file is image

c#,asp.net,asp.net-mvc

You can't do this: string.Contains(string array) Instead you have to rewrite that line of code to this: if (file == null || formats.Any(f => file.Contains(f))) And this can be shortened down to: if (file == null || formats.Any(file.Contains)) ...

System.net.http.formatting causing issues with Newtonsoft.json

c#,asp.net,asp.net-mvc,json.net

Does the assemblyBinding tag have proper xmlns schema? Check if the issue you are encountering is same as Assembly binding redirect does not work

How to get Display Text from EnumDropDownListFor on post?

c#,asp.net-mvc,enums,html-helper

You can write an extension method for Enums to return Display value of an Enum value: public static class DataAnnotationHelpers { public static string GetDisplayValue(this Enum instance) { var fieldInfo = instance.GetType().GetMember(instance.ToString()).Single(); var descriptionAttributes = fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false) as DisplayAttribute[]; if (descriptionAttributes == null) return instance.ToString(); return (descriptionAttributes.Length > 0) ?...

Seeding fails validation for nested tables (validates_presence_of)

ruby-on-rails,ruby,validation,ruby-on-rails-4,associations

Found this : Validating nested association in Rails (last chapter) class User belongs_to :organization, inverse_of: :users validates_presence_of :organization_id, :unless => 'usertype==1' end class Organization has_many :users accepts_nested_attributes_for :users, :reject_if => :all_blank, :allow_destroy => true end The documentation is not quite clear about it but I think it's worth a try....

Knockout JS Validation not working

javascript,asp.net-mvc,knockout.js

At this line var EmployeeKoViewModel.errors = ko.validation.group(self); you are trying to create a variable, but the syntax is like creating an object with a property which is of course invalid. In order to fix this you can initialize your object first: var EmployeeKoViewModel = {}; EmployeeKoViewModel.errors = ko.validation.group(self); if (!EmployeeKoViewModel.errors().length...

How to get started with Visual studio 2012

c#,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,visual-studio-2012

Download this book "Microsoft ASP.NET 4 Step By Step" by George Shepherd.I found it very helpful.It will address all the issues you raised here.Thank you.

Strange situation, Visual Studio debugging ran through action to view but nothing returned to browser

c#,jquery,ajax,asp.net-mvc,razor

error: function () { alert("EmptyResult returns."); debugger; $.post('@Url.Action("Delete2", "Customers")', { id: clickedId }); }, Result of a post does not refresh your page, so quick fix is to genrate an anchor with URL to controller action add id parameter and click on it or change window location with controller/action/clicked id....

Unable to find the auto created Database

c#,asp.net,asp.net-mvc,entity-framework

If you don't specify a database name then the connection will use the default database for the user, in this case it's integrated security so it's your Windows login. As you likely have full system admin on the server the default database will be master so you will find all...

How to add validators for @Html.TextBox() without model

asp.net-mvc,asp.net-mvc-4

Add data-val and data-val-required attribute for Html.TextBox() as shown below. <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> @using (Html.BeginForm("","")) { @Html.ValidationSummary() @Html.TextBox("bill_address", null, new { @class = "form-control valid", @data_val = "true", @data_val_required = "Billing Address is required" }) <input type="submit" value="Click"...