Add string of text to DropDownList in ASP.NET MVC - asp.net-mvc-3

In an ASP.NET MVC 3 Web site I have a view with the following code (Razor):
#Html.DropDownList("SessionYear", new SelectList(ViewBag.SessionYears as System.Collections.IEnumerable, "", "", Model.SessionYear), String.Empty)
ViewBag.SessionYears is an IEnumerable<int>.
The output is something like this:
<select id="SessionYear" name="SessionYear"><option value=""></option>
<option>2013</option>
<option selected="selected">2012</option>
<option>2011</option>
<option>2010</option>
</select>
That's great, however, what I'd like to do now is add a bit of text to the text displayed in the drop down list, so each option looks a little like this:
<option>2013-2014</option>
<option selected="selected">2012-2013</option>
I've tried playing around with the different options, but none are working, and I've exhausted the overloads.
Can I do this with the DropDownList helper, or do I need to implement this in a different way?
EDIT: And while I could probably convert SessionYears to an object that has an int and string to resolve this, I'd prefer not to. But if that's what I've got to do, that's what I'll do.
EDIT 2:
The code I'd expect to work is:
#Html.DropDownList("SessionYear", new SelectList(ViewBag.SessionYears as System.Collections.IEnumerable, "", (Model.SessionYear + "-" + (Model.SessionYear + 1)), Model.SessionYear), String.Empty)
However, I get the following error:
DataBinding: 'System.Int32' does not contain a property with the name '2012-2013'.
Which I suppose makes sense, since Model.SessionYear is an int. This is also why I'm thinking I have to create a new object that contains SessionYear as an int and then some other property that contains (SessionYear + "-" + (SessionYear + 1)) (as I've done in the past with other models).
But I would expect for there to be an easier way.

I am not sure if I'm understanding the question right but why aren't you setting the dataValueField and dataTextField?
Maybe build your SelectList something like this:
#Html.DropDownList("SessionYear", new SelectList(ViewBag.SessionYears as System.Collections.IEnumerable, Model.SessionYear, Convert.ToChar(Model.SessionYear) + Convert.ToChar(Model.SessionYear + 1), Model.SessionYear), String.Empty)

Related

ASP.Classic Getting value from input to POST parameter

Please excuse me if this question is dumb.
I need to get an input value and pass it in a POST parameter like follow:
SQL = "[proc_Happy]" & Request.Cookies("UserID")& "," & Request.Form("MYINPUTFIELD")
I have tried hardcoding MYINPUTFIELD with (it worked!):
SQL = "[proc_Happy]" & Request.Cookies("UserID")& "," & 54555152
My input in the asp page looks as follow:
<input type="number" name="MYINPUTFIELD " id="MYINPUTFIELD" value="<%=MYINPUTFIELD%>">
Things I have tried:
Getting the value with JS - failed.
Notes:
MYINPUTFIELD is an int
Is your input field in a form, i.e. is it between <form...> and </form> tags? If no, that's your problem right there. If yes, what does the <form...> tag have in it? Does it say method='get'? If yes, then your inputs are being put in the querystring, not the form object. For Request.Form(...) to work, your form needs to say method='post'.
If you need this code to work with both form methods, you can do something like
dim MyInputField
MyInputField = Request.Querystring("MyInputField")
If MyInputField = "" Then MyInputField = Request.Form("MyInputField")
'make the "OMGSQLINJECTION!!1!" people just go away already
'(note to such people: he's using a frigging stored procedure.)
If Not Isnumeric(MyInputField) Then
MyInputField = 0
End If
SQL = "[proc_Happy]" & Request.Cookies("UserID")& "," & MyInputField

how to concatenate text & view model item

Hi I am trying to join two bits of information on an MVC view to create one long string on screen. I have a bit of text within <\a> and a returned variable in the model (model.item.number).
Currently I have the following in my view :
a>01643< / a> #Html.DisplayFor(modelItem => item.phone)
this returns the correct value, but gives a space between 01634 and the item.phone value. I have tried wrapping the whole thing with < a > but to no avail.
I am sure this is dead simple & so easy in webforms. can someone put me out of my misery and let me know how to do this.. I'm an MVC3 noob.
Remove the space:
a>01643</a>#Html.DisplayFor(modelItem => item.phone)
Or, Just write the value:
a>01643< / a>#Html.DisplayText(Model.item.phone)

ASP.NET MVC 3.0 automatically adding rows and cols attribute

We have some code that calls the Html.TextArea(string name, IDictionary<string, object> htmlAttributes) extension method. This method is adding rows="2" cols="20" automatically. I see in Reflector that these are internal values (part of an implicitRowsAndColumns dictionary).
Is there a way to force ASP.NET MVC to not output these attributes? I don't understand why their code would do this in the first place since CSS is a much better way to establish the size of a textarea.
Try including new { rows = "", cols = "" } to your TextAreaFor call.
It is likely because validators require the rows and cols attributes. But just because they are required does not mean they need to have a value.
stackoverflow.com/questions/2649283/avoid-textarea-rows-cols-error

Correct way to populate select box using Prototype-JS

I would like to populate a select box with data fetched by ajax.
The initial HTML code looks like:
<select id="myid" name="myname">
</select>
I need to avoid innerHTML and other such workarounds. I tried using appendChild but it did not seem to work.
I am really new to prototype, so I really dont know how to go about it.
Assuming you wanted to add all members of a self-created object as key-value pairs to a select element, you could do that this way:
var data = {
a: 'Peter',
b: 'Paul',
c: 'Mary'
};
$('mySelect').update($H(data).map(function(o) {
return '<option value="' + o.key + '">' + o.value + '</option>';
}).join(''));
​
You find a jsFiddle of it here.
The basic idea behind the code is, that you create your option elements from the given data object, by transforming every one of them into a string. That is done by the map method.
The $H will transform the data object into a Prototype Hash object, which comes in handy here, as it will pass a { key, value } object to the first parameter of it's map invocation.
After transforming all elements to Strings, you just have to join them by an empty String (or whatever non-HTML code you like, \n would do as well) to be able to use them for the update method.
To be honest, Element#update uses innerHTML so that is actually not a workaround. It's just one way to do it.

How To Elegantly Handle JSON Objects in Responses From Ajax Requests?

I'm really new to using JSON to handle my Ajax Request and Response cycle. I've previously used just plain old parameters passed as POST data and I've rendered straight HTML in the response which was then placed into the DOM. As I've looked at various examples and read through various tutorials, it seems like a fairly common practice to simply build a string from the JSON object mixed with HTML that's been hard coded into the string and then assign the string as innerHTML to some element.
A common example looks something like this:
var jo = eval(req.responseText);
var strTxt = '<span>' + jo.f_name + ' ' + jo.l_name + '</span><br/>' + 'Your Age Is: ' + jo.age + '<br/>';
$('myDiv').innerHTML = strTxt;
Is there a more elegant (or correct) way of handling the JSON response so that I'm not hard coding HTML in the javascript? Or is this pretty much how people do it?
P.S. Links to tutorials or other sources are appreciated.
I steer away from writing a lot of HTML within JavaScript strings. I prefer separation of structure from data manipulation. The better alternative is to place that code in the page, load the values based off the ID's, and show/hide it if necessary:
<div id="codeBlock" style="visible=false;">
<span id="val1"></span>
<br/>
<span id="val2"></span>
<br/>
</div>
............
<script>
var jo = eval(req.responseText);
$('val1').innerHTML = jo.f_name + ' ' + jo.l_name;
$('val2').innerHTML = 'Your Age Is: ' + jo.age;
$('codeBlock').show();
</script>
That might not be exactly what you want to do but you get the idea.
You could create the elements in the DOM using javascript instead of just dropping them into the innerHtml of the DIV, something like the following (untested):
var mySpan = document.createElement("span");
var spanContent = document.createTextNode(jo.f_name + ' ' + jo.l_name);
mySpan.appendChild(spanContent);
var myBr = document.createElement("br");
mySpan.appendChild(myBr);
var otherSpanContent = document.createTextNode('Your Age Is: ' + jo.age);
mySpan.appendChild(otherSpanContent);
mySpan.appendChild(myBr);
$('myDiv').appendChild(mySpan);
You could check out a templating engine such as PURE - may be a bit hard to get into at first but it supports many major javascript frameworks (and DOMAssistant which is nice) and separates html from the data.
The objects created from JSON are standard Javascript objects, therefore you can easily use jQuery selectors to create or access DOM elements and insert content from your JSON objects.
eg.
// Create a new span element and set its text
var personSpan=$("<span>").text(jo.f_name + ' ' + jo.l_name);
// Append the span to the existing myDiv element
$("myDiv").append(personSpan);
// Create a new div element (better then br) and set its text
var personDiv=$("<div>").text("Your Age Is: " + jo.age);
// Append the new div to the existing myDiv element
$("myDiv").append(personDiv);

Resources