Html.DropdownlistFor not showing in view - asp.net-mvc

I have this line in my view.aspx I am not using razor:
<p style="color:Red">
<% Html.DropDownListFor(model => model.AllSundays, new SelectList(Model.AllSundays)); %>
</p>
When I run my program and view source there is nothing there.
I am making use of the ViewModel in my action I have:
var allSundaysInThisMonth = new SundaysInMonthViewModel
{
AllSundays = sundays.Select(x => new SelectListItem
{
Value = x.ToString("dd-MM-yyyy"),
Text = x.ToString("dd-MM-yyyy"),
})
};
var selectedSunday = new SundaysInMonthViewModel{
SelectedSunday = thisMonthSundays.Where(x => x < now)
.Last().ToString("dd-MM-yyyy")
};
return View(allSundaysInThisMonth);
thanks

You should use <%= and no comma at the end if you want to output something to the response, otherwise you are only executing server side code that never gets flushed to the response:
<%= Html.DropDownListFor(
model => model.AllSundays,
new SelectList(Model.AllSundays)
) %>
Also AllSundays seems to already be an IEnumerable<SelectListItem> so you don't need to feed that to a SelectList in the view:
<%= Html.DropDownListFor(
model => model.AllSundays,
Model.AllSundays
) %>
Also (and this is extremely important), you should not use the same property as both the selected value and the available values. Currently you are using AllSundays twice. That's absolutely wrong. The DropDownList helper expects as first argument a scalar property on your view model to hold the selected value and an IEnumerable<SelectListItem> property as second argument that will hold the selected values.
So what you want is:
<%= Html.DropDownListFor(
model => model.SelectedSunday,
Model.AllSundays
) %>

Related

Rails check_box_tag - get all the values checked in view(haml) file

So I have multiple checkboxes on my page. I collect all of them like shown in the code below. I would like to access the values of the array before passing it on to the controller
= check_box_tag "names[]", ob.name, false, class: 'cbx'
I am able to pass them with my older code
%fieldset.actions
= form.submit "Upgrade", :class => 'button'
Logs:
Processing by SomeController#create as HTML Parameters:
{"utf8"=>"✓",
"names"=>["ron", "jacob"], "commit"=>"NameButton"}
Ok. So i would like to access all values in my haml files. Is there a way before i submit my form, I can access which checkboxes are selected.
I would like to pass the names[] to my controller as a parameter.
=link_to script_name1, { :action => 'create', :names => 'dontknowhowtopassnames[]' }, :method => :post
Rails version - 3.2.17
You can do that using Javascript.
The exact implementation depends on what exactly you want to do with those values, but you could, for example, use the change event to track and maintain an array of all checked values :
/*
* should properly init this array if some of your checkboxes are already
* checked when the form is loaded
*/
var names = [];
$(document).ready(function() {
$(document).on('change', '.cbx', function() {
var name = $(this).val();
var idx = names.indexOf(name);
if ($(this).prop('checked') && idx === -1) {
names.push(name);
} else if (!($(this).prop('checked')) && idx >= 0) {
names.splice(idx, 1);
}
});
});
Updated with complementary answer:
To submit a form with a link instead of a button:
In your view, replace
%fieldset.actions
= form.submit "Upgrade", :class => 'button'
with
= link_to "Submit", "#", :class => 'submit_link'
Then in your Javascript, add the following inside the $(document).ready body:
$(document).on('click', 'a.submit_link', function(e) {
$(this).closest('form').submit();
e.preventDefault();
});
And that's it. You're making your life very complicated by trying to serialize the form data on your own while the form's submit() method can take care of it for you. You can serialize data on your own, and it's sometimes useful, for instance when dealing with AJAX, but in your case the default submit() is perfect for the job.

How to use trim on DropdownlistFor

Benefit Set: </label><br />
<%: Html.DropDownListFor(model => model.bvODSMapping.Benefit_Set, Model.BenefitSet,new {id="BSet", style = "width:230px;" })%>
When I am using model=>model.bvODSMapping.Benefit_Set.Trim()
I am getting Value Can not be null.
can anybody help me out how to trim the string?
Thanks
I guess it would be the best to trim the values before passing the model to your view.
Nevertheless, this might help:
#Html.DropDownListFor(
model =>
model.bvODSMapping.Benefit_Set,
Model.BenefitSet.Select(
item =>
new SelectListItem
{
Selected = item.Selected,
Text = item.Text.Trim(),
Value = item.Value
}),
new { id = "BSet", style = "width:230px;" })

RoR Displaying associated records based on select menu option

I am new to RoR and I am looking for a way to dynamically display values in some text fields depending on the option chosen from a select menu in a form. The associated records are stored in another table. Hopefully in a way AJAX can be used such that it wouldn’t require a page refresh. I have seen examples in which select menus are dynamically changed according to values of select menus but not text fields.
Thanks,
Alex
PS: I am using rails 3.
Here's how I did it. I'm a Rails beginner too, so this may not be the best/most efficient way, but it works:
JS:
$('#select_box_id').live('change', function() {
var select_field_val = $('#select_box_id').val();
if(select_field_val == "") select_field_val = "0";
$.get('/some_controller_action/' + select_field_val, function(data) {
$('#text_field_div').html(data);
});
return false;
});
Controller:
def some_controller_action
#some_processing...
result = whatever
render :partial => "my_partial", :locals => { :text_field_value => result }
end
View:
<div id="text_field_div">
<%= render :partial => 'my_partial', :locals => { :text_field_value => "" } %>
</div>
Partial:
<%= text_field_tag :text_field, text_field_value %>

What's the most elegant way of using a partial view to render a comma delimited set of items?

I need to render a list of Person objects, say, in a comma delimited format using a Partial View in ASP.NET MVC. My problem is that when rendered using the following code:
<% foreach (var person in Model) { %>
<%= Html.ActionLink<PersonController>(c => c.Edit(person.PersonID), Html.Encode(person.Name)) %>,
<% } %>
I get a trailing comma after the last item. What's the most elegant/least stupid way to have this list of persons rendered without the last comma?
My two options so far, in no order, would be:
Use JavaScript to remove the trailing comma on the client side
Manually create the list using code, instead of markup, in the partial view
Neither of these options appeal to me - any ideas?
Thanks!
How about:
<%=String.Join(
",",
Model.Select(
person=>
Html
.ActionLink<PersonController>(
c => c.Edit(person.PersonID),
Html.Encode(person.Name)
)
)
.ToArray()
)%>
(untested)
<% bool first = true;
foreach (var person in Model) {
if (first) first = false; else Response.Write(","); %>
<%= Html.ActionLink<PersonController>(c => c.Edit(person.PersonID), Html.Encode(person.Name)) %>
<% } %>
I think, instead of a foreach, you're going to have to iterate through the persons collection using a conventional for loop. That way, you can detect the last iteration through the loop and avoid the last comma.
<% { int count=Model.Persons.Count();
for (int i=0; i< count; i++) { %>
<%= Html.ActionLink<PersonController>(c => c.Edit(Persons[i].PersonID), Html.Encode(Persons[i].Name)) %>
<% if (i < count) { Response.Write(","); }
} %>
Uses LINQ Aggregate to concatenate comma-delimited links without appending a trailing comma.
<%= Model.Select(person => Html.ActionLink<PersonController>(c => c.Edit(person.PersonID), Html.Encode(person.Name))
.Aggregate((links, link) => links + ", " + link) %>

Setting maxlength and other html attributes using ASP.NET MVC helper methods

Currently when I want to set html attributes like maxlength and autocomplete, I have to use the following syntax:
<%= Html.TextBox("username", ViewData["username"], new { maxlength = 20, autocomplete = "off" }) %>
Is there any way to do this without having to explicitly set the ViewData["username"] portion? In other words, I want to rely on the helper method's automatic loading routine rather than having to explicitly tell it which field to load up from the ViewData.
Just pass "null" as second parameter:
<%= Html.TextBox("username", null, new { maxlength = 20, autocomplete = "off" }) %>
yes but you have to use ViewData.Model instead of ViewData.Item()
the code in your controller should look like this (sry 4 VB.NET code)
Function Index()
ViewData("Title") = "Home Page"
ViewData("Message") = "Welcome to ASP.NET MVC!"
Dim user As New User
Return View(user)
End Function
now you can do this in the view
<%=Html.TextBox("username", Nothing, New With {.maxlength = 30})%>
note that the user object has a public property username
hth
I used construction as below:
<%= Html.TextBox("username", "", new { #maxlength = "20", #autocomplete = "off" }) %>
For Setting max length of TextBox you can pass "" or null for Second Parameter and set html attributes(maxlength) as third parameter
<%=Html.TextBox("username", "", new { #maxlength = 10 }) %>

Resources