.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

ActionFilter Returning To View On Handled Error (MVC2)

Posted By:      Posted Date: October 13, 2010    Points: 0   Category :ASP.Net

Hi People,

I have a action filter:

  public class ExceptionActionFilterAttribute : ActionFilterAttribute
        public void OnException(ExceptionContext filterContext)
            if ((filterContext.Exception != null) && (!filterContext.ExceptionHandled))
                var validationError = filterContext.Exception as EntityValidationError;

                if (validationError != null)
                    foreach (var error in validationError.ValidationErrors)
                        var errorMessage = error.PropertyName + " " + error.Message;
                      filterContext.Controller.ViewData.ModelState.AddModelError(error.PropertyName, errorMessage);

                    filterContext.ExceptionHandled = true;

                    // Would liek to return back to the view so it can display the changes made to modelstate above.
} } } }

Once the action filter handles the validation, instead of redirecting to another pages is it possible just to return the view associated with the action with the updated modelstate?

Basically this is to handle business validation exc

View Complete Post

More Related Resource Links

WebFaultException throwing a "not handled by user code" error and returning an HTTP 500 to the clien

I am trying to return a BadRequest and simple message when implentation throws an error in a WCF REST service, but the WebFaultExcption itself is throwing an exception and returning an HTTP 500 instead. Any ideas on why this might be happening? Here is a short code snippet: [WebDispatchFormatter] [WebHelp(Comment="Initiate an immediate or callback appoinment request")] [WebInvoke(UriTemplate = "InitiateContact", Method = Verbs.Post)] public string InitiateContact(AppointmentRqst rqst) {      string ret = string.Empty;      rqst.DeviceId = Helper.GetHttpAuthHdrDeviceId();      try      {          ret = impl.InitiateContact(rqst);      }      catch (Exception ex)      {          throw new WebFaultException<string>(ex.Message, HttpStatusCode.BadRequest);      }      return ret; }

Custom Control Design view error



I have created a custom control from scratch and it works fine as in you can build the project that uses it and it works fine at runtime. Problem is when you go to design view the control shows an error in the place of where the control should be rendered.

Error: '<SomeValue>' Could not be set to '<SomeProperty>'

This shows up on all my custom set properties. These properties are created as basic as possible. I can give the properties values in Source view and run the app just fine. I can even add a Onclick event. If I don't set any custom properties the control will render fine in Design view. It's only when I set a value to a custom property.

Property Code Example:

public string Text
                string ret = "";
                object obj = ViewState["Text"];
                if (obj != null)
                    ret = obj.ToString();
                return ret;
                ViewState["Text"] = value;

I've even removed the Category and Description tags with no difference.

I don't know if what I said makes sens, but I hope it

show data in grid view error Arithmetic operation resulted in an overflow.



i have a table there is 17 columns in 17 column 3 are number and other are varchar . when i try to display all data of that column error occures.

one more intersting think is when i try to display 6 column then grid show there data an no more error occures. 

when i run my project this error occures in grid view

Arithmetic operation resulted in an overflow. 

Entity Data Model and database view returning the same columns as there are in a table


When adding a stored procedure into the Entity Data Model I can select whether the procedure returns a scalar, a (new) complex type or one of the entity types I already defined. 

How do I do something similar for a view?

I mean assuming I have a view like this

CREATE VIEW FilteredFoos as SELECT Foo.* FROM Foo join ... WHERE ...

(that is a view that implements some involved filtering, but returns all columns from one table) how do I add it to the project so that I can use the entity set, but get the Foo objects, not some new FilteredFoo objects.

var foos = myDB.FilteredFoos.Include("Bar").ToList();

foreach (Foo foo in foos) { ...

Thanks, Jenda

Very strange error reported in View (Might be a bug in VS2k8?)



As I say in the title of my post this "may" be a bug in VS2k8 Pro, I have seen these strange little things happen before but whenever you utter the word "bug" people tend to get defensive, so I say it "may" be ;)

Basically I have two List(Of MyOwnClass) and I am going to enumerate through these lists on my view.

I add the Import statement to the top of my view so that my custom class can be used on it.

I add a very simple loop,

                    <%For Each CPDCourse As Download In CType(ViewData("CPDAvailable"), List(Of Download))%>
                        <td style="width:100%">
                            <a href="<%=CPDCourse.URL%>">
                            <a href="<%=CPDCourse.URL%>">
                                <img style="border:none;" alt="View Image" src="../../Content/Images/digitaltraining/view.jpg" />

Returning custom error messages with an UserNamePasswordValidator

Ok, my head hurts from banging it against the wall. I'm new to WCF, I have searched for a solution for days, please help a desperate fellow programmer if you can :-( I have a WCF service hosted in IIS, I implemented a UserNamePasswordValidator, and it seems impossible to find a way to return a custom error message to the client when the user is not allowed in, this blows my mind. I have searched everywhere, many are asking the same question since 2006 and so far I haven't found an answer that works. If you are thinking of replying that it is not secure to return a custom error message to an unauthenticated client, please save yourself some time and don't do it. There are multiple enterprise business scenarios that this is required. Just in our organization an account could be locked out, in which case the user must be directed to the IT department to get it unlocked, it could be that the credentials are correct but the user hasn't paid their fees in which case they must be directed to the appropriate department, or it could even be that the user tried to access the service during a time of the day in which the service is not available. From searching around, I have tried doing the things below in the Validate method, however the client always receives a MessageSecurityException, which contains none of the custom messages that were originally thrown, neither in the object,

error in MVC2 on empty string form fields which are required: "This property cannot be set to a null

In model I have:[DisplayName("ISBN")] [Required(ErrorMessage = "ISBN is required.")] [StringLength(50, ErrorMessage = "ISBN book must have max {1} chars.")] [DisplayFormat(ConvertEmptyStringToNull = false)] public string isbn { get; set; }But when I submit form with empty field ISBN I have an error - ConstraintException: This property cannot be set to a null value.I have find that other people have the same problem and they say that debbugger in VS2010 works wrong - yes ?http://p2p.wrox.com/book-professional-asp-net-mvc-2/79788-constraintexception-unhandled-user-code.html#post259245http://efreedom.com/Question/1-3129080/Server-Side-Validation-REQUIRED-String-Property-MVC2-Entity-Framework-Workhttp://mvcmusicstore.codeplex.com/workitem/6604

Error calling WCF service that is returning list.".Debugging resource strings are unavailable ......

Ok.this is just making me frustrated... Here is step by step of what I am trying to do (& not able to) 1. I am calling WCF service hosted in a SharePoint 2010 site from a silverlight app in same domain (So no cross doman I guess). 2. I use Linq to Sharepoint for querying the DB. 3. I am having a list "machines" in Sharepoint 2010 that is having a lookup column from Other list called "part" 4. My WCF method GetAllMachines() works perfectly well when it skips the lookup column "partname" & returns List of type machineitem. 5. But problem occurs when I add machineitemobject.parts.partsname in my Linq to Sharepoint query . My service gives the error not found Async_ExceptionOccurred] Arguments: Debugging resource strings are unavailable." 6. Note that return type of my Method is List<machinesitem> 7. The point to note here is that I use SPMETAL tool to generate the LINQ class that maps the lists . So When I try to query the lookup column it tries to add List item of the type class & that is what causing the error. Is it because I am not using datacontract in my service (but it returns the strings & all private members of machines list e.g. name,title etc) Is it making the attribute Serialisable will solve the error ??? I am kind of lost in it ...Plss help!!   Thanks

Data Source View Gives incorrect Error--Different Data Type

Hi, I'm creating a report model (2008 R2).  I am trying to create a relationship between two tables.  One FKs to another--same name and type (tinyint) columns.  But the Data Source View editor doesn't allow this, giving the message "...source and destination column have different data types".  But the columns are the same types.  I ahd this once before  acouple of years ago and don't remember how I got around it. Does anyong have ideas?  

The specified view is invalid error when browsing for images

Hello All, Currently using MOSS 2007 publishing site and using the CMS elements to publish content to the web.  One of our users is experiencing a strange problem whereby when they try to insert an image into the Sharepoint content editor using the Insert Picture functionality they get the following error when trying to browse to an image: The specified view is invalid.   at Microsoft.Sharepoint.SPViewCollection.get_Item(String strDisplayName) at Microsoft.Sharepoint.Publishing.Internal.States.AssetPickerDetailState.InitGridView(GridView grid) at Microsoft.Sharepoint.Publishing.Internal.States.AssetPickerDetailState.Configure(SMObjectList objectlist) at Microsoft.Sharepoint.Publishing.Internal.WebControls.SMObjectList.Handle_LoadCompleteEvent(Object sender, EventArgs e) at System.EventHandler.Invoke(Object sender, EventArgs e) at System.Web.UI.Page.OnLoadComplete(EventArgs e) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) Only one user is experiencing this problem, others are fine. Does anyone have ANY ideas what is causing this issue or how to fix it? Thanks

Grid view update error

Server Error in '/WebSite6' Application. Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:1. Add a "Debug=true" directive at the top of the file that generated the error. Example:   <%@ Page Language="C#" Debug="true" %>or:2) Add the following section to the configuration file of your application:<configuration>    <system.web>        <compilation debug="true"/>    </system.web></configuration> Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode.Important: Running applicatio

While trying to view a report in integrated mode i see an unsupported RPL stream error

Trying to deploy a report in integrated mode on MOSS 2007. SQL server version is 2008 R2. I see the following:   ??? ?????????? ? ????м???? ?? ??????? ????????? ??????. ?????????? ?????????????м?? ?????? ?????? RPL: 34.62.1836345404. ??????м?? ??????: 10.3.     Yes i know its in russian. Another fail of Microsoft not being able to see the error codes and strings in english language, makes finding solutions even harder, because first you must find HOW is this called in english, then look for solution. Okay so, i found out that it is actually transalted into: unsupported RPL stream version detected 34.62.1836345404 expected version 10.3 Now, everywhere around the webs they say that this is because my Add-in is out of date and i need new RS addin for MOSS 2007.  But the link is dead!    For example, here http://social.msdn.microsoft.com/Forums/en-US/sqlreportingservices/thread/61357765-52aa-4085-9ee0-4cb494a6c3ad   @For SQL 2008 R2 together with WSS 3.0 / MOSS 2007, you need the SQL server 2008 november CTP add in:  http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=44bda62c-0cda-4a99-8d0a-d7fe06b39422 But the link is dead and there is no hint as to what happened.   The only valid link i found is this: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=65606fdd-093f-4c

NetUserGetInfo/NetLocalGroupGetInfo returning error 1722

I have the following code (VB.NET) which is designed to determine if a given account name refers to a local group or a user account. This will only be called for accounts/groups on a machine, not a domain. Module netapi Private Declare Function NetUserGetInfo Lib "Netapi32.dll" ( _ ByVal ServerName As String, _ ByVal UserName As String, _ ByVal level As Integer, _ ByRef BufPtr As IntPtr) As Integer Private Declare Function NetLocalGroupGetInfo Lib "Netapi32.dll" ( _ ByVal ServerName As String, _ ByVal GroupName As String, _ ByVal level As Integer, _ ByRef BufPtr As IntPtr) As Integer Declare Unicode Function NetApiBufferFree Lib "Netapi32.dll" _ (ByRef buffer As IntPtr) As Long Public Function GetPrincipalType(ByVal MachineName As String, ByVal AccountName As String) As String Dim bufPtr As IntPtr Dim lngReturn As Integer = NetUserGetInfo("\\" & MachineName, AccountName, 0, bufPtr) Console.WriteLine("NetUserGetInfo return value = " & lngReturn) Call NetApiBufferFree(bufPtr) bufPtr = IntPtr.Zero If lngReturn = 0 Then Return "User" End If lngReturn = NetLocalGroupGetInfo("\\" & MachineName, AccountName, 0, bufPtr) Console.WriteLine("NetLocalGroupGetInfo return value = " & lngReturn) Call NetApiBufferFree(bu

Performancepoint designer error - Update View Failed

I've created a scorecard that uses dynamic members.   I'm no longer able to design it. When I click on 'Update' to retrieve the scorecard I get the following error:   The last attempt to update this view failed. Try retireving the view again by pressing Update in the Edit tab. If you are still not able to retrieve it, contact your administrator. Error Details: An unexpected system error has occured. Additional details have been logged for your administrator.   The event log says: An unexpected error occurred.  Error 56822. Exception details: System.ServiceModel.CommunicationException: The maximum message size quota for incoming messages (100000000) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element. ---> System.ServiceModel.QuotaExceededException: The maximum message size quota for incoming messages (100000000) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element.    --- End of inner exception stack trace --- Server stack trace:    at System.ServiceModel.Channels.HttpInput.ThrowMaxReceivedMessageSizeExceeded()    at System.ServiceModel.Channels.HttpInput.GetMessageBuffer()    at System.ServiceModel.Channels.HttpInput.ReadBufferedMessage(Stream inputStream)    at System.S

save codes error in form view tool

hi i use this code in form view(at INSERT button)  for save data into SQL serverInsertCommand="INSERT INTO Debtor (AccNo, CompanyName, Desc2, RegisterNo, Address1, Address2, Address3, Address4, PostCode, AreaCode, Phone1, Phone2, Fax1, Fax2, NatureOfBusiness, WebURL, EmailAddress, DeliverAddr1, DeliverAddr2, DeliverAddr3, DeliverAddr4, DeliverPostcode, Attention, SalesAgent, DebtorType, DisplayTerm, CreditLimit, CurrencyCode, UDF_Shipvia, UDF_freigh, UDF_SourceIn, UDF_ProductEnq)VALUES ( @AccNo, @CompanyName, @Desc2, @RegisterNo, @Address1, @Address2, @Address3, @Address4, @PostCode, @AreaCode, @Phone1, @Phone2, @Fax1, @Fax2, @NatureOfBusiness, @WebURL, @EmailAddress, @DeliverAddr1, @DeliverAddr2, @DeliverAddr3, @DeliverAddr4, @DeliverPostcode, @Attention, @SalesAgent, @DebtorType, @DisplayTerm, @CreditLimit, @CurrencyCode, @UDF_Shipvia, @UDF_freigh, @UDF_SourceIn, @UDF_ProductEnq)"> it's show error at:-        Must declare the scalar variable "@AccNo".if i run the application without add (AccNo,....)VALUES(@AccNo) into above codes it's working good..AccNo is into drop down list control..

Error message in opening a view after Replication server restored

Hi, Yesterday Replication was broken as Publisher was down. After it was restored, I tried to open a view in Subscriber and I get the following error message [Microsoft] [ODBC SQL Server Driver] [SQL Server] Login failed for user 'Repl admin'   Any suggestions to get around this problem.   Thanks in advance -Jaya

Office Web Apps - View Word doc in the browser error

I have been trying to figure out why I keep getting this error everytime I try to view a word docx document in the brower of my SharePoint Server 2010 site. Word Web App cannot open this document for viewing due to an unexpected error.  To view this document, open it in Microsoft Word. Error Id: 855eacd0-6974-424f-b0f9-a305ab62af6d, 20100916200545 Any help or direction to resolving the problem would be greatly appreaciated.Daryl Gilbert II
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend