knockout.js ASP.NET data-bind to dropdownlist (Visual Studio 2008) - asp.net-mvc-2

I'm attempting to data-bind a value to an ASP.NET DropDownList but the server complains that it doesn't recognize the data-bind attribute:
<%=Html.DropDownList("accountSiteInstanceId", ViewData["degreePrograms"] as SelectList, new { #data-bind = "value: DegreeProgramId" } ) %>
I get the following error:
Compiler Error Message: CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

The problem is the dash. Use dictionary based notation:
<%= Html.DropDownList("accountSiteInstanceId", ViewData["degreePrograms"] as SelectList, new Dictionary<string, object>
{
{"data-bind",
"DegreeProgramId"}
}) %>

change the dash into an underscore and it will convert it back to dash on runtime.

Related

Are digits allowed in a knockout.js custom binding name?

I have an application with a custom binding declared like
ko.bindingHandlers.slideContent2 = {
init: ...,
update: ...
}
and I use that in my html with (among other things)
<div data-bind="slideContent2: true"></div>
It works and produces no errors. Today I discover that the new knockout.js syntax checker in Netbeans 7.4 thinks that <div data-bind="slideContent2: true"> is in error. It objects to the digit 2. If I remove that, it thinks the name is fine. Looking around web examples, I haven't found an example of a digit used in the name of a custom binding.
Are digits legal in custom binding names? Is the Netbeans checker being overenthusiastic?
From the Knockout point of view every valid JavaScript identifier name is a valid custom binding handler name.
So you can have digits in custom binding handlers. For the full identifier name reference you can check: Valid identifier names
However from the Netbeans syntax checker point of view only letters are allowed in custom binding names.
For reference check out the source of KODataBindLexer (I've added some comments)
case IN_KEY:
if (!Character.isLetter(c)) { // the character 2 is not a letter
if (c == ':') {
state = State.AFTER_KEY;
input.backup(1); //backup the colon
return tokenFactory.createToken(KODataBindTokenId.KEY);
} else if (Character.isWhitespace(c)) {
state = State.WS_AFTER_KEY;
input.backup(1); //backup the ws
return tokenFactory.createToken(KODataBindTokenId.KEY);
} else { // 2 is not a the colon and not a whitespace so it returns Error:
state = State.INIT;
return tokenFactory.createToken(KODataBindTokenId.ERROR);
}
}
//stay in IN_KEY
break;

mvc2 dropdownlist dynamic parameters

<% string disabled="new {disabled='disabled'}"; %>
<%= Html.DropDownList("clientId", someObject, disabled)%>
In the above code I want the text disabled to be replaced by what ever value I set that string to. When I check the HTML source on the page, I see that new {disabled='disabled'} has been added as a new item in the dropdown list instead of a property. How do I fix this?
The third parameter of DropDownList helper must be an object that contains the HTML attributes or object of type IDictionary<string, object>.
This is the proper solution:
<% var disabled = new { disabled = "disabled" }; %>

How to get the value of lambda expression in asp .net mvc2?

I have a action result method where it gives values from the database and Iam passsing this values to the view and the values will be populated in the textboxes but i have radio button to be selected depending on the value of the database,example if the value is male then radiobutton as to be selected else radiobutton female aas to be selected.I have written the code
<% if(model=>model.Gender) {%>
<%= Html.RadioButtonFor(model => model.Gender, "Male", "Checked")%> Male
<%} else { %>
<%= Html.RadioButtonFor(model => model.Gender, "Female", "Checked")%> Female<%} %>
but Iam getting a error like "Cannot convert lambda expression to type 'bool' because it is not a delegate type" .Please tel me how to check the value of Gender and make selection accordingly.
Assuming you've got access to the model at that point, you don't need the lambda expression at all:
// Or whatever
<% if (model.Gender == Gender.Male) {%>
However, I think it's unlikely that this is how you're meant to use RadioButtonFor. I'd expect it to be able to pick up the right button to check automatically.

ModelState.AddModelError - How can I add an error that isn't for a property?

I am checking my database in Create(FooViewModel fvm){...} to see if the fvm.prop1 and fvm.prop2 already exist in that combination; if so, I want to add an error to the modelstate, then return the whole view. I tried:
public ActionResult Create(FooViewModel fvm){
if (ThatComboAlreadyExists(fvm)) {
ModelState.AddModelError("Model", "There is already one like that");
return View(fvm);
}
}
...but I get no display of errors in the Html.ValidationSummary, which is where I assume they would appear. I have the suspicion that "Model" is not the right key, but I haven't been able to find anything a la Google.
I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:
ModelState.AddModelError(string key, string errorMessage);
but use an empty string for the key:
ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");
The error message will present itself in the <%: Html.ValidationSummary() %> as you'd expect.
You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.
As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using
<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>
and
ModelState.AddModelError("Email", Resources.EmailInUse);
Putting the model dot property in strings worked for me: ModelState.AddModelError("Item1.Month", "This is not a valid date");
Try Using Below Answer for consistent Output Format :- new ValidationProblemDetails()
if (!ModelState.IsValid) {
ModelState.AddModelError("ErrorKey", "ErrorValue");
return BadRequest(new ValidationProblemDetails(this.ModelState));
}
Output Format:
{
"errors": {
"ErrorKey": [
"ErrorValue"
]
},
"title": "One or more validation errors occurred.",
"status": 400,
}

Display empty textbox using Html.TextBoxFor on a not-null property in an EF entity

I am using Entity Framework (v4) entities. I have an entity called Car with a Year property of type integer. The Year property does not allow NULL. I have the following in my Create view:
<%= Html.TextBoxFor(model => model.Year) %>
I am required to return a new Car object (due to other requirements) in my HttpGet Create action in the CarController.
Currently, a zero is displayed in the Year textbox because the Year property does not allow NULL. I would like to display an empty textbox in the Create view. How do I do this?
Use Html Attributes Overload. In razor it would be:
#Html.TextBoxFor(model => model.Year, new { Value = "" })
Try this instead:
Html.TextBox("Year", "")
If you are using the strongly typed TextAreaFor helper, then there is no direct way to set a default value. The point of the strongly typed helper is that it binds the text area to a model property and gets the value from there. If you want a default value, then putting in the model would achieve that. You can also just switch to the non-strongly typed TextArea helper. It gives you more a bit more flexibility for cases like this:
#{
var defaultValue= "";
}
#Html.TextArea("Model.Description", defaultValue, new { Value = "added text", #class = "form-control", #placeholder = "Write a description", #rows = 5 })
Try this is you are trying to append to your field or want to modify an existing field with an empty TextBoxFor.
Html.TextBoxFor(model => model.Year, Model.Year="")