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

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.

Related

Play Framework Form Error Handling

This is my view file containing the form that has to filled in by the user:
#helper.form(call) {
#helper.input(resumeForm("surname"), '_label -> "Surname") { (id, name, value, args) =>
<input name="#name" type="text" value="#value" placeholder="Enter your surname">
}
}
This is my custom field constructor:
#(elements: helper.FieldElements)
#if(!elements.args.isDefinedAt('showLabel) || elements.args('showLabel) == true) {
<div class="input-with-label text-left">
<span>#elements.label</span>
#elements.input
</div>
} else {
#elements.input
}
Now I have a dilemma. When the entered value doesn't clear validation, I need to add the class field-error to the input and I need to add data-toggle, data-placement and title. However, I don't know of any way to check if there are errors for the specific field. What is the best way to implement this? I already looked at using inputText or something but that is basically the same as the base input thus also does not have access to any errors. I'm also unable to alter the HTML of the elements.input inside the field constructor.
Have a look at play documentation: Writing your own field constructor.
You can check on errors with #if(elements.hasErrors) within the template of your custom field constructor.
<div class="input-with-label text-left #if(elements.hasErrors){field-error}">
...
Edit:
You can pass the error state of your field via the args parameter to your input. From the play docs:
Note: All extra parameters will be added to the generated HTML, except for ones whose name starts with the _ character. Arguments starting with an underscore are reserved for field constructor argument (which we will see later).
You need to cast to the matching type though.
#input(resumeForm("surname"), '_label -> "Surname", 'hasErrors -> resumeForm("surname").hasErrors) { (id, name, value, args) =>
<input name="#name" type="text" value="#value" placeholder="Enter your surname"
class="#if(args.get('hasErrors).map(_ match { case x:Boolean => x}).get){field-error}">
}

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" }; %>

Bind a form field in Play 2.0 with a constant value?

I have a scala form with several fields.The fields in the form map to the member variables of a Java class. I want to bind one of the fields(say userId) with a value (I dont want the user to enter values for this field. Instead i want to pass this as a parameter to the scala template). However, i was unable to manually bind a form field. Any help is highly appreciated.
See the sample below for easier understanding :
`#(itemForm: Form[Item], user: User)
#import helper._
#main("Item list") {
#if(user != null) {
#form(routes.Application.newItem()) {
#itemForm("userId") = #user.id /**I want to bind the userId form field */
#inputText(itemForm("title"))
#inputText(itemForm("description"))
#inputText(itemForm("price"))
<input type="submit" value="Create">
}
}
}`
In this case it would be better to pass it as action's argument (remember to modify routes declaration)
#form(routes.Application.newItem(user.id)){
....
you can also just use common html
<input type="hidden" name="userId" value="#user.id" />
edit:
Validation in action.Note: it doesn't make sense to display errors on the page next to hidden field, so you do not need placeholders for error messages. It's up to you to pass VALID value into the hidden field. Displaying validation errors to user who can not change the value of hidden field is bad conception.
public static Result newItem(){
Form<ItemModel> itemForm = form(ItemModel.class).bindFromRequest();
if (itemForm.hasErrors(){
return badRequest(newItemView.render(itemForm));
}
itemForm.get().save();
return ok("Your new item is saved...");
}

Outputting data whilst in a partial view

I have some MVC2 code that loops a collection of type Product held within the view model. Each time I want to output the data I have to use <%: %> along with using <% %>, for example:
<% foreach (Product item in Model.ProductsCollection) {
if (item.doesExist == true) { %>
<%: item.name %>
<% } %>
Is there any way to still output item.name without having to close & open tags, e.g. in classic asp we used response.write()?
I appreciate the need to encode data using <%: %>, and am not wanting to bypass this, just wanting to output the encoded data without needing the bracket overhead.
Thanks
You can use Response.Write() in conjunction with Html.Encode()
<% foreach (Product item in Model.ProductsCollection) {
if (item.doesExist == true) {
Response.Write(Html.Encode(item.name));
}
} %>
Not in aspx view engine, sir.
Check out MVC3 rc2 and #razor view engine.
#razor is the Man.

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="")