Change View in mvc based on dropdownlist item selection - javascript

I have a dropdownlist on a View as:
<p>
#Html.DropDownList("Status", new List<SelectListItem>
{
new SelectListItem{ Text = "Show Active", Value = "0" },
new SelectListItem{ Text = "Show Deleted", Value = "1" }},
new
{
onchange = #"
var form = document.forms[0];
form.action='deletedDistricts';
form.submit();"
})
and I am referring it to controller action as:
[HttpPost]
[ActionName("deletedDistricts")]
public ActionResult deletedDistricts()
{
var d = hc.deletedDistricts.ToList();
return View(d);
}
but JavaScript is giving a runtime error as:
0x800a138f - JavaScript runtime error: Unable to set property 'action' of undefined or null reference
I am not very good at JavaScript. Any idea why this code is throwing Null reference?

Well I can't see that you would have a form associated with a dropdown, make sure that it's wrapped with:
#using(Html.BeginForm("deletedDistricts", controllerName, FormMethod.Post)) {
// drowpdown here
}
And remove form.action='deletedDistricts';
conrollerName should be name of your controller as a string.

Let's read the error you are getting once again:
0x800a138f - JavaScript runtime error: Unable to set property 'action'
of undefined or null reference
OK, now let's read your code once again to see where you are attempting to set an action property. Looks like that's happening right over here:
form.action='deletedDistricts';
Alright, so it seems like the form instance is undefined at this stage. So the obvious next step you would like to look at is where is this form instance coming from. And you wouldn't be surprised to find this line of code of yours:
var form = document.forms[0];
Cool, you seem to be attempting to retrieve the first <form> element in your DOM. But do you have such element? Did you ever use the Html.BeginForm helper to render an HTML form? Answering those simple questions would definitely put you on the right track. Don't hesitate to inspect the markup you are generating in the browser. I am sure this would help you figure out the missing bits.

Related

Cannot read property of undefined of an apparently NOT undefined - SOLVED

I am using a control of Telerik (AutoCompleteBox) which contains an embedded dropdown control that can be accessed through the property _dropDown. I am using the dropDownItemDataBound event to trigger the following code:
var autoComplete = $find("<%= RadAutoCompleteBox1.ClientID %>");
console.log(autoComplete._dropDown._items);
When I click over the [] in the console I get this (that is expected):
[]
0: b.RadAutoCompleteBox.DropDownItem
_attributes: c.AutoCompleteBoxAttributeCollection {_data: {…}, _keys: Array(0)}
_element: null
_template: null
_text: "Chevrolet TRAVERSE "
_value: "GM1"
Thus I supposed that I could do this:
var autoComplete = $find("<%= RadAutoCompleteBox1.ClientID %>");
console.log(autoComplete._dropDown._items[0]._text); // Chevrolet TRAVERSE
console.log(autoComplete._dropDown._items[0]._value); // GM1
Instead I get:
Uncaught TypeError: Cannot read property '_text' of undefined
It doesn't make sense to me because since autoComplete._dropDown._items is obviously an array (and it's NOT undefined!) I should be able to access it by indexing it and get the property contents. Not?
EDIT:
Following the suggestion of #ChrisG that mentioned that perhaps the arry was STILL empty when I tried to log the data to the console, I changed my code into the event to this (to give it a little time and see what happens):
waitAndDisplay();
function waitAndDisplay(timeout = 50) {
setTimeout(function () {
var autoComplete = $find("<%= RadAutoCompleteBox1.ClientID %>");
console.log(autoComplete._dropDown._items[0]._text);
}, timeout);
}
Indeed it worked however it doesn't seem to be a safe approach. Any idea on how to ENSURE that the data is fully loaded before to try to read it?
SOLUTION:
I was after the suggestion of #ChrisG on use a callback to data loaded and figured that I goofed in the documentation of the control because in fact there IS an event that triggers after the dropdown is fully loaded, so I will post the solution here. This way the callback function to be used is OnClientRequested and not the dropDownItemDataBound as I did initially:
function OnClientRequested(sender, eventArgs) {
var myarray = eventArgs.get_data();
console.log(myarray[0].Text);
console.log(myarray[0].Value);
}
It will return the proper data.

Unable to get value from model in javascript

I am new in MVC environment and I just started upgrading a website.
Problem
Object reference not set to an instance of an object.
Explanation
I have javascript function for a button in the view and I am trying to get a property value CurrentPageNo from the associated model as shown below.
$('#pPrevious').on('click', function (event) {
event.preventDefault();
this.blur();
if (ShowBusy()) {
getPageIndexChanging(#Model.CurrentPageNo-1);
}
});
I am referring to the model as below:
#code
ViewBag.Title = "Home"
End Code
#ModelType HomeModel
#Using (Html.BeginForm("Index", "Home", FormMethod.Post, New With {.id = "indexForm", .name = "indexForm"}))
Try
#Html.AntiForgeryToken()
etc...
When I put a breakpoint in the model it doesn't work.
What Am I doing wrong in this situation ?
It is difficult to Get c# model data in your javascript code.
Simply you can add the value in a text box that is hidden and get value with getElementById in your javascript code.

$(document).ready(function() stops working as soon as i assign value to variable ( var userid = ${userid}; )

I just want to be able to access variable userid in document.ready function. It's accessible in the JSP page but not in jQuery. I am able to print value of ${userid} on the same JSP page but not in jQuery. I have passed userid obj with model and view object to this JSP page. However I am not able to access that object.
$(document).ready(function(){
var examid = ${userid};
alert("Hello !");
//alert(username);
});
If the value of ${userid} is a string then you need to wrap it in quotes, otherwise you'll be getting a syntax error thrown in your JS code.
For example var examid = '${userid}';
– Rory McCrossan Apr 4 at 10:45

Fabric js extending toObject with custom properties, loses default ones

Befor posting this I've been looking up in here as in many other places, but I can get to have this working fully.
All I need is to be able to save some custom properties in all the shapes. The properties are : uuid, and rt_attributes.
Therefore, as by manual I added this code :
fabric.Object.prototype.toObject = (function(toObject) {
console.log(toObject)
return function() {
return fabric.util.object.extend(toObject.call(this), {
uuid: this.uuid,
rt_attributes: this.rt_attributes
});
};
})(fabric.Object.prototype.toObject);
which does work fine, up to a certain degree.
the problem comes when I serialize in json and load back.
the custom attributes are in , but shapes like the IText raise an exception such as :
fabric.js:22199 Uncaught TypeError: Cannot read property 'split' of undefined
Looking into the dumped json I can see the .text attribute is not exported. So My fear is that overriding the toObject I lose some of the custom attributes of the default object.
Of course I can redefine it in my toObject function with all the missing trims, but I though that
fabric.util.object.extend
would have done that for me.
Can someone point me on what I'm doing wrong ?
thanks.
L.
p.s
here is a snippet of the outcome json:
{"type":"i- text","originX":"left","originY":"top","left":29,"top":677,"width":107,"height":22.6,"fill":"rgba(255,255,255,1)","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","transformMatrix":null,"skewX":0,"skewY":0,"uuid":"04af6ab4-4eb1-432b-f46a-93b11a92292d","rt_attributes":[["fontFamily","text"],["fontSize","int"],["fill","color"],["opacity","float"],["top","int"],["left","int"]],"styles":{}},
as you can see there's no text field., but uuid and rt_attributes are in.
Finally found the proper way:
fabric.Object.prototype.toObject = (function (toObject) {
return function (propertiesToInclude) {
propertiesToInclude = (propertiesToInclude || []).concat(
['uuid','rt_attributes']
);
return toObject.apply(this, [propertiesToInclude]);
};
})(fabric.Object.prototype.toObject);

Trying to test whether element has attribute without directly assessing the element

Trying to create query object on clicks on various buttons by sending attributes on html called "attr-{{foo}}" which get their name from an ng-repeat or some other means. I wanted on controller that first tests if the element has all attributes that map onto the keys of the query object in the scope, and continue this if else chain down to having only one attribute; however, when I tried this, I would get the error "cannot find .value of 'null'", as I was testing with
(below you will find a snippet that is representative of my controller)
vm.openFoos = function (event) {
if (event.target.attributes.getNamedItem('attr-foo').value &&
!event.target.attributes.getNamedItem('attr-bar').value) {
var obj = {
foo: event.currentTarget.attributes.getNamedItem('attr-foo').value,
name: $routeParams.name
} else if {
(event.target.attributes.getNamedItem('attr-foo').value &&
event.target.attributes.getNamedItem('attr-bar').value) {
var obj = {
foo: event.currentTarget.attributes.getNamedItem('attr-foo').value,
name: $routeParams.name,
bar: event.currentTarget.attributes.getNamedItem('attr-bar').value
}
}
data.getReviews(obj)
.success(function (data){$log.debug(data)}).error(function(e){$log.debug(e)});
};
This works if I click on elements with both attr-foo and attr-bar (as by the convention of this testing from most strict case of having attributes to least, I know if I had written the if statements in reverse I would get the error "cannot find value of null". Sample HTML:
<span class="one" ng-click="vm.openFoos($event) attr-foo="foooo">Click FOOO</span>
<span class="two" ng-click="vm.openFoos($event) attr-foo="fo" attr-bar="bar">Click FOO BAR</span>
Clicking span.one throws the error "cannot find value of null" but clicking span.two works fine.
I do not want to write a controller for each instance of the combinations of keys in my query appearing on various html attributes; however, I'm getting this error.
instead of using
if (event.currentTarget.attributes.getNamedItem('attr-thing').value ....
use
if (event.currentTarget.attributes.getNamedItem('attr-thing') ....
When
event.currentTarget.attributes.getNamedItem('attr-thing')
does not exist, obviously one cannot take the value of it!
Could you be looking for hasOwnProperty?
object.hasOwnProperty("attrname"); // Yields true or false.

Categories