ASP.Net MVC null reference exception with TextArea name - asp.net

I have a TextArea html helper method I'm calling in a foreach loop. Basically, when I initially load the View it works fine, but when i reload the View and load postback data, the same TextArea throws a NullReferenceException and yet the variable I'm using in the TextArea as the name of the TextArea is not null. I've attached a picture below for demonstration:
Sorry if it's difficult to see, the blue arrow below is pointing to the variable used to name the TextArea. Again, it works on initial load, but it errors out on postback when the page is reloaded. I'm not sure what's going on.

Are you using custom validation in your application? If so, this is a known issue in MVC 1 (fixed for MVC 2). See http://forums.asp.net/p/1377232/2908610.aspx for more context and a workaround.

This link seemed to provide the solution. Turns out I was not setting the model value after adding errors to the model state, so it was searching for the model values to place back into the TextArea, they were null of course, hence the error. Very obscure error in my opinion. This StackOverflow post was also very enlightening.

Related

Sitecore controller rendering causing StackOverflowException

I am trying to do a simple controller rendering with Sitecore 8 and for some reason it's producing a StackOverflowException on the line within the main layout markup that contains the reference to the placeholder it is to be rendered in. This seems to crash the worker process, but you can see the stack overflow on debugging the process:
Here is my very basic controller:
And here is my controller rendering definition:
Reproduction notes:
This is occurring in a vanilla Sitecore 8 installation (rev. 150427 -installed via SIM).
The MVC project is also vanilla -created with empty ASP.NET project, then NuGetting in MVC 5.1.
Web.config & Global added to project from the Sitecore site root in wwwroot.
FYI - everything is absolutely fine doing a view rendering - it's just controller renderings that seem to be causing a problem
So the problem was actually pretty simple in the end.
Returning a ViewResult when the view is intended as a partial view (which all Sitecore renderings will be) then you must set the layout property in the markup to null:
#{
Layout = null;
}
Otherwise MVC will try to wrap the layout file around it, which of course contains your Sitecore placeholder, which causes an infinite loop and crashes the worker process with a StackOverflowException.
So in the context of Sitecore, either return a PartialViewResult or return a ViewResult with the layout set as null.
I guess there is something missing in placeholder setting, could you check in path sitecore/layout/placeholder setting?
There should be a placeholder key which you are trying to use.
Hope this will help
Cheers!!
I think the issue can be with method View() being called without any parameters which can cause re-rendering the whole Sitecore page again.
Try to add parameter to View() like that:
return View("/Views/Courses/Index.cshtml");
Or whatever is the path of the view you want to return.
EDIT:
As #David Masters found, for some reason the issue is with calling View instead of PartialView method with the full path as a parameter. The correct code is:
return PartialView("/Views/Courses/Index.cshtml");

RegisterExpandoAttribute - Throwing Error

Recently, I discovered that using: someControl.Attributes.Add("customAttr", "customVal") is not compatible with all web browsers. The recommended registration for custom attributes is:
Page.ClientScript.RegisterExpandoAttribute(someControl.ClientID, "customAttr", "customVal")
Okay, here's the problem. I am using a ListView to generate a custom control. In certain scenarios, the ListView must be refreshed/recreated. When this happens, and a ListView item attempts the register (in this case, re-register) the expando attribute, the page throws the following error:
An entry with the same key already exists.
Obviously RegisterExpandoAttribute() does not behave like the Page.Cache object where if a key already exists, the current value is overwritten. I can easily hack my way past this problem but I wonder if there is a more elegant solution to this. For example, there is no method like: Page.ClientScript.IsExpandoAttributeRegistered(...)
Any ideas?
If you're creating a custom control, try doing the RegisterExpandoAttribute call during the control PreRender. I was having issues with the attribute still being registered if the control had been removed and doing that fixed my issue. I would imagine that if you're calling RegisterExpandoAttribute in the PreRender for the control then it shouldn't be called more than once per page load.

Problem with asp.net C# focus, page_load

I'm really new to asp.net and have a couple of issues I'm trying to get fixed. I have some programming experience, but it is not asp.net. However, I've been able to follow the code enough to make other changes in the code to fix other issues.
The first is this:
I'm working with a form that has a calculate amount method that gets called when the user inputs a value in an amount text box. The same method gets called when the next control, number of payments, has a value.
So in the two controls:
onTextChanged="ctrlName_textChanged"
Then in the code behind, the textchanged method does:
calculateAmount();
The problem is after the amount is calculated and returns, the focus seems to get reset and the user has to tab all the way back through the form to the place they were.
The textboxes in question are in a panel that starts out hidden and is made visible conditionally.
My apologies if I have not used the proper .net terminology.
It looks like the same issue may be causing my second problem. When the user types in an amount and then tabs and quickly adds the number of payments, you can see the amount get calculated correctly and very shortly displays the proper total in the total amount text box. However, even though it shows for that short time, the tab order again gets reset as well as the total amount value.
I've looked at different methods to try and fix the focus issue.
In the textchanged method, I tried using something like:
Session["myval"] = "someval";
Then tried to check against that in Page_Load with something like:
if(Session["myval"] != null) {
this.NextControl_Name.Focus();
}
but it didn't ever work correctly.
I also tried to set a cookie in that same textchanged method using something like this:
Response.Cookies["myval"].Value = "somevalue";
Then tried to check that in Page_Load using something like the previous if block above but using Request.Cookies["myval"] as the source.
Is there a good reference with some really clear code samples I can look at for this type of implementation?
Thank you in advance,
C.
Sounds like you have a postback problem...
Remember that the web is stateless. This means that when you have a web page rendered out in .NET and you attach an event that executes serverside code... it does an HTTP POST back to the server which is effectively a new page request. The Page_Load method will fire again as well as your bound event. So your onTextChanged event is firing a new request back to the server. This is why you see the focus reset and why when you tab quickly, the value seems to disappear magically.
You can do one of several things, you can implement the UpdatePanel in the AjaxControlToolkit
http://www.asp.net/ajax/ajaxcontroltoolkit/samples/
you can use PageMethods and do your validation with javascript and jQuery (or other js library)
see page method info http://www.geekzilla.co.uk/View30F417D1-8E5B-4C03-99EB-379F167F26B6.htm
Hope this helps

How to force Flex validation when a container is displayed

I have a Flex 3 app with a view in a viewstack, and that view must only be created when requested. I have declared validators for each of the controls on the view and I have created a method called checkAllValid() which runs Validator.validateAll(). This works great when I'm actually using the controls (using the change or focusOut events), but how can I get checkAllValid() to run when the view is first displayed to the user, so that they are immediately shown what is invalid once the data is populated in the controls?
I have tried putting the call in various events on the view itself (e.g. creationComplete, updateComplete, show, activate, etc.) but it always shows the following error when I start the application:
'The source attribute must be specified when the property attribute is specified.'
I have also tried setting the creationPolicy on the view to "all" but this does not help.
Some of the validators are only enabled when the form is in a certain state, but I have eliminated that as being the potential problem by commenting out all of my validators except for this most simple one:
<mx:Array id="validators"><mx:StringValidator id="val_Address1" source="{Address1}" property="text" required="true" triggerEvent=""/></mx:Array>
The checkAllValid() method is as simple as follows:
private function checkAllValid():void{
var validationErrors: Array = Validator.validateAll(validators);
}
I have also tried calling the single validator directly rather than using validateAll and the result is the same.
Please help! There must be a way I can force the view to validate when it is shown....
(by the way it's in the Cairngorm MVC framework and I have data bound to the controls)
Got it! I added similar validators to another view and they worked fine. What was the difference? The method that called checkAllValid() was being called on the creationComplete event of an internal container - not the main view component.
So in the end it was nothing to do with the validation itself - just me not fully understanding the creation order.
I'll leave the question on here just in case someone encounters a similar problem with the creation order.

Dynamic Control loading at wrong time?

This one is a little... odd. Basically I have a form I'm building using ASP.NET Dynamic Data, which is going to utilize several custom field templates.
I've just added another field to the FormView, with it's own custom template, and the form is loading that control twice for no apparent reason. Worse yet, the first time it loads the template, the Row is not ready yet and I get the error message:
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control
I'm accessing the Row variable in a LinqDataSource OnSelected event in order to get the child object...
Now for the wierd part: If I reorder the fields a little, the one causing the problem no longer gets loaded twice.
Any thoughts?
EDIT: I've noticed that Page_Load gets called on the first load (when Row throws an exception if you try to use it) but does NOT get called the second time around. If that helps any...
Right now managing it by just catching and ignoring the exception, but still a little worried that things will break if I don't find the real cause.
EDIT 2: I've traced the problem to using FindControl recursively to find other controls on the page. Apparently FindControl can cause the page lifecycle events (at least up to page_load) to fire... and this occurs before that page "should" be loading so it's dynamic data "stuff" isn't ready yet.
You aren't referring to something in Page_Load that is set in OnSelected, are you? Something like your row object. OnSelected is a postback event and occurs after Page_Load. It's the only thing I can think of that might cause your exception when the row is not ready.
Start commenting things out in your code behind until either everything is commented or your control no longer loads twice.
If it is still doing it, start unhooking things in the control itself. Eventually, you'll get to the actual issue.

Resources