How do I distinguish RadioButtons? - c#

I have a for-loop with a RadioButton at each iteration. My problem is I don't know how to distinguish every single RadioButton once I validate my form (how to retrieve their value?) . I have a model for printers :
public class Printer{
public int id{ get; get;}
public string printerName { get; set; }
}
Which itself is part of another model :
public class FinalSiteModel
{
public string name{ get; set; }
public List<Printer> printers{ get; set; }
public bool selected { get; set; }
}
Then as I pass it to the view :
for(var i = 0; i < Model.printers.Count() ; i++)
{
#Html.RadioButtonFor(m => m.selected, new { Name = "groupRadio"});
#Html.Label(Model.printers[i].printerName);
}
I think something is wrong with the way I wrote my RadioButton. I initially used the boolean selected inside of the PrinterModel but my problem then came from the fact that the radiobuttons didn't group since I used
#Html.RadioButtonFor(m => m.printers[i].selected, new { Name = "groupRadio"});
and this bit : m => m.printers[i].selected created a different name for each radiobutton, hence when I check several radiobuttons at the same time, which I don't want.
I'm guessing I should add a parameter to RadioButtonFor ?

Your radio buttons need a value to bind to your selected property. However that property needs to be int, not bool
public class FinalSiteModel
{
...
public List<Printer> Printers { get; set; }
public int SelectedPrinter { get; set; }
}
and then in the view
foreach(var printer in Model.Printers)
{
<label>
#Html.RadioButtonFor(m => m.SelectedPrinter, printer.Id, new { id = "" })
<span>#printer.Name</span>
</label>
}
Note the 2nd parameter of RadioButtonFor() adds the value attribute based on the Id property of Printer, and the new { id = "" } removes the id attribute which would otherwise be invalid because the method generates duplicates
The value of SelectedPrinter will now contain the Id of the selected Printer when you POST your form.
As a side note, never attempt to change the name attribute using new { Name = "groupRadio" } - it would not bind to your model.

Related

Why won't my Edit screen validation allow null?

I added a field to a view model for a Document that should allow the user to associate it with a Tenant. It works fine if the user does assign a tenant, but if they select the null option from the dropdown, then the validation tells me that "The ItemID field is required.", where ItemID is a field on TenantViewModel.
It occurs to me that perhaps I'm using editor templates wrong - I'm trying to select from a list of tenants, not edit a tenant. If that's wrong, let me know, and maybe suggest a better way to get the dropdown.
namespace TenantPortal.Models
{
public class DocumentViewModel
{
...
[UIHint("SelectTenant")]
public TenantViewModel Tenant { get; set; }
}
public class TenantViewModel
{
private Tenant _ten = null;
public int ItemID { get; set; }
public string Display_Name { get; set; }
public string Legal_Name { get; set; }
...
}
}
Editor Template: SelectTenant.cshtml
#using CMS.DocumentEngine.Types.Tenantportal
#using TenantPortal.Models
#model TenantViewModel
#{
Layout = null;
var opts = new SelectList(TenantProvider.GetTenants(), "ItemID", "Display_Name");
}
#Html.DropDownListFor(model => model.ItemID, opts, "(none)")
If you use data annotations you can add validation to your model.
See my example below:
public class TenantViewModel
{
private Tenant _ten = null;
[Required]
public int ItemID { get; set; }
[Required]
[MaxLength(30)]
public string Display_Name { get; set; }
public string Legal_Name { get; set; }
...
}
For further information about data annotations check this
Also, on your code/controller-action side, you need to use ModelState.IsValid check in order to verify whether your model is valid or not
Your ItemID field is an int so it does not allow null values so the model validation fails. Try changing it to int? (a nullable int). If a value is not set in the form, then the value will be null, but if a value is selected, the ItemID will be the selected value.
I ended up adding another property to my document view model named TenantID, having it communicate with the Tenant property behind-the-scenes, and creating SelectLists for TenantID dropdowns on both Create and Edit views. It's less elegant than I would like, but it works.

Populate single dropdown from two tables

The scenario is:
Data is stored in database in project and neighbourhood tables both.
Now, i want to populate dropdown with project id and project name and neighbourhoodId and neighbourhood name.
i am right now sending through viewBag like this:
ViewBag.NeighbourhoodId = new SelectList(allNeighbourhood(), "Id", "NeighbourhoodName");
on view page, getting dropdown populated like this:
#Html.DropDownList("Locations", ViewBag.NeighbourhoodId as SelectList, "Select a location")
Now,how to send another viewBag in this dropdownList.
Second ques, My dropdown is in partial view So, i am sending data to partial view like this:
#Html.Partial("_CommentBoxSection",new Neighbourhood())
how to send new Project()) along with neighbourhood. Is there any overload of partial where i can send both of them.
i have seen some posts relating to this title but they are something different
I have recently tried this:
public class ProjectAndNeighbourhoodListItemViewModel
{
public Project Project { get; set; }
public Neighbourhood Neighbourhood { get; set; }
public string ProjectName { get; set; }
public int Id { get; set; }
public bool IsSelected { get; set; }
// public IEnumerable<SelectListItem> ToSelectListItem { get; set; }
public SelectListItem ToSelectListItem()
{
return new SelectListItem
{
Text = Project.ProjectName,
Value = Neighbourhood.Id.ToString(),
Selected = IsSelected
};
}
}
and on view page directly,
#model #model IEnumerable<ProjectAndNeighbourhoodListItemViewModel>
#Html.DropDownList("Locations", Model.Select(m => m.ToSelectListItem()), "Select a location")
but getting System.ArgumentNullException value cannot be null i have no code in controller do i have to pass something in controller too
Do not use ViewBag to pass values to your view, use ViewModels instead, it is much cleaner. The ViewModel is also a good place to create your SelectListItems. Create or map the ViewModel in your controller.
// ViewModel for a single selectable entry
public class ProjectAndNeighbourhoodListItemViewModel {
public string ProjectName { get; set; }
public long NeighbourhoodId { get; set; }
public bool IsSelected { get; set; }
public SelectListItem ToSelectListItem() {
return new SelectListItem {
Text = ProjectName,
Value = NeighbourhoodId.ToString(),
Selected = IsSelected
}
}
}
In your Razor View:
#model IEnumerable<ProjectAndNeighbourhoodListItemViewModel>
#* Would be even better to use a wrapper model that contains the collection of list items as property! *#
#Html.DropDownList("Locations", Model.Select(m => m.ToSelectListItem()) , "Select a location")

How to populate dropdown menu from my local hosted database?

I'm really stumped right now. I've been stuck with this problem for a number of days now and frankly, I'm getting sick and tired of it.
I have this database table: https://gyazo.com/9d1b014ecdba1e244c2f6957b6d9397c
(notice FlightsTable)
My goal is to populate a dropdown menu based on the values from the "Departure" section.
I've tried lots of things and yet I still cannot get to grips with it.
Here's my model:
public class FlightModel
{
public int FlightID { set; get; }
public string Departure { set; get; }
public string Arrival { set; get; }
public int NumberOfSeats { set; get; }
public int NumberOfFlights { set; get; }
}
Controller:
public ActionResult BookFlight()
{
return View();
}
FlightDBEntities (from the FlightsDBModel)
namespace Project_v3.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class FlightsDBEntities : DbContext
{
public FlightsDBEntities()
: base("name=FlightsDBEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<FlightsTable> FlightsTables { get; set; }
}
}
Screenshot of the files: http://gyazo.com/31b447387f349fbbe541f44a358c3096
How do I make the dropdown work in my view for BookFlight? I'm really struggling with this so step-by-step solutions so I can understand every step would be greatly appreciated. Please and thank you.
There are a few ways to do this, this is an example:
You'll need something that actually creates your selectlist:
public SelectList GetAsSelectList()
{
var depts = from f in db.FlightsTables
select new SelectListItem
{
Value = f.Departure,
Text = f.Departure
};
return new SelectList(depts, "Value", "Text");
}
If departures are held in their own table, then it would be better to select them from there, using the Id primary key field as the selectlist's value field
I've assumed that the selectlist will be shown on the same page as FlightModel. If this is the case, then your model needs a property for the selectlist:
public SelectList DepartureList { get; set; }
Your controller method needs to create a FlightModel instance, populate it with whatever you want to show (including the selectlist) and pass it to the View:
public ActionResult BookFlight()
{
var model = new FlightModel
{
DepartureList = GetAsSelectList()
};
return View(model);
}
Depending on what you want the user to do with the selectlist, you display it in the view like this:
#Html.DropDownList("Departure", Model.DepartureList)
In your controller, select the distinct departures
IEnumerable<string> departures = db.FlightsTables.Select(f => f.Departure).Distinct();
and assign to to a ViewBag property (or better, use a view model with a property for the SelectList)
ViewBag.DepartureList = new SelectList(departures);
and in the view (unsure what the property you want to bind to - you have not shown your model for the Booking)
#Html.DropDownListFor(m => m.YourProperty, (SelectList)ViewBag.DepartureList, "-Please select-")
I suspect you may need to modify your flight table. You have a ID column but the have a column for number of flights. Surely you would need information about departure and arrival times for each flight?
Edit
Further to comments, your booking model may look something like.
public class BookingVM
{
public List<FlightModel> FlightList { get; set; } // to display available flights
public string Departure { get; set; } // bind to DepartureList
public int FlightID { get; set; } // bind to FlightID in a dropdown that displays the arrival locations
public int Seats { get; set; } // number of seats booked
public SelectList DepartureList { get; set; } // unique departures
}
You would need to handle the .change() event of the Departure dropdownlist, use ajax to pass the selected departure to a controller method that returns the flightID and arrival locations (and probably the number of available seats for each flight) and use that to populate the second dropdownlist (bound to FlightID and displaying the arrival locations).

What is available in the controller from a post action in a dropdownlist

Trying to unpack some inherited code and I am new to ASP.NET. My question:
What is available in the controller from a post action in a dropdownlist in C# (ASP.NET MVC5)?
Here is what I have in the view:
#using (Html.BeginForm("SignUp", "Location", FormMethod.Post))
....
#Html.DropDownListFor(
model => model.Member.PillarId, new SelectList (Model.Pillars, "Id", "Title"))
Here is the MemberViewModel:
public class MemberViewModel : IValidatableObject{
public int? LocationId { get; set; }
public int? PillarId { get; set; }
}
Here is the Member model:
public class Member
{
public int Id { get; set; }
public string Name { get; set; }
public int? LocationId { get; set; }
public int? PillarId { get; set; }
public String PillarTitle { get; set; }
Here is the Member model constructor(s):
public Member() { }
public Member(MemberViewModel member)
{
PillarId = member.PillarId;
///
}
Here is the Controller
public ActionResult SignUp(MemberViewModel member){///}
My form is correctly pulling the information from the DB to display, as well as posting correctly to the DB via the Controller. I do not want to change the visual options for the user to choose from (i.e. I think ListBox is out?).
Rather, I want to assign both Member.PillarId as well as the Member.Title based on their choice and have it available in the Controller for non-DB operations.
What is currently available in the SignUp method in the Controller? Can I call Model.Pillars.Title? Is it member.PillarId.Pillars.Id? If not, how can I assign it dynamically based on the user choice?
There are views and modelviews flying around in this code, and I am not sure what is available...
SO has a bunch of answers on the DropDownList, so here's a sampling of articles that are somewhat related to what I am getting at...
* This answer
* ListBox
* ListBoxFor: not MVC dynamic
* SelectList Constructor: Not MVC
With a dropdownlist the only value that will come back is the value of the selected item when posting back.
If you want something else to come back you would need a hidden field on the page and bind a change event listener to the dropdown to set the title in the hidden field
public class MemberViewModel : IValidatableObject{
public int? LocationId { get; set; }
public int? PillarId { get; set; }
public string Title { get; set;}
}
#using (Html.BeginForm("SignUp", "Location", FormMethod.Post))
....
#Html.DropDownListFor(
model => model.Member.PillarId, new SelectList (Model.Pillars, "Id", "Title"))
#Html.HiddenFor(model => model.Title);
javascript
$('#idofdropdown').on('change', function()
{
var selectedTitle = $(this).find(":selected").text();
$('#Title').val(selectedTitle);
});
How to get selected title from a drop down list: Get selected text from a drop-down list (select box) using jQuery
Then in your controller your viewmodel will have the title text inside the Title string :)

Trying to create a dynamic enough model to handle dynamic questions

I am trying to create a dynamic model for a set of questions that are pulled dynamically into my app.
I want to set my input types equal to a question id (which is unique). Then I want to associate those answers with a value field in my model.
I have this model:
public class QuestionViewModel
{
public int? Id { get; set; }
public string QuestionType { get; set; }
public string Text { get; set; }
public List<QuestionOptionViewModel> Options { get; set; }
}
public class QuestionOptionViewModel
{
public int? Id { get; set; }
public string Text { get; set; }
public string StringValue { get; set; }
public bool OptionValue {get; set;}
}
So I tried to do a texboxfor like below. I was hoping that this would set the form name = "id" and then set the value to my model property StringValue. But it doesn't work.
#for (int i = 0; i < #Model.Options.Count; i++)
{
<div class="col-lg-4">
<label for="#Model.Options[i].Text">#Model.Options[i].Text</label>
#Html.TextBoxFor(o => Model.Options[i].StringValue, new { name = Model.Options[i].Id, #class = "form-control", placeholder = "" })
</div>
}
Let me walk you through the model being given to me pseudo code style. It should explain what I want to do.
QuestionViewModel
int = 1
questionType = Text
Text = What is your name?
QuestionOptionViewModel
int = 1
Text = FirstName
StringValue = *I want to set the response here*
OptionValue = *If it was a radio I want to store bool here*
int = 2
Text = LastName
StringValue = *I want to set the response here*
OptionValue = *If it was a radio I want to store bool here*
So I added into the model the StringValue part. I want to catch the responses there so I can dynamically have a trace that this questions input box would have the name of QuestionOption int. And store the value in StringValue (since text in this example).
I am confused on the appropriate way to do this in C# MVC? What would be the correct way to handle dynamically created questions that are pulled into a web page. I can easily pull them out using my model. But I am unsure the proper way to store them back into the model.
As requested here is a screen grab of a single question.

Categories

Resources