how to implement Checkboxes in MVC 3? - c#

Hi I am quiet new on MVC 3 with C#. I am using entity framework and database first approach to generate code automatically. But the problem is, I tried to find information about inserting checkboxes in MVC3 using C# code but I could not get helpful website.
I can insert the check box using HTML tags:
<input type="checkbox" name="Science" id="s1" value="Science" />
<input type="checkbox" name="Biology" id="b1" value="Biology" />
<input type="checkbox" name="Chemistry" id="c1" value="Chemistry" />
But how do I insert the check box value inside the database and validate that only one single checkbox is selected?
e.g I have a table named Paper where I have:
Paper_Title - textbox
Paper_Details - textbox
Category - Checkboxes (e.g. Science, biology, chemistry)
Comments - textbox.
Submit-button

Use radio button and then have an enum for Categories(say enumCategories). Have a model Category of type enumCategories and then in the postback set the model based on which radio button is checked.
Hope this gives you an elaborate idea on the approach.

I don't think that checkboxes are what you need here, they're more used for multi-selectable items. Either radio buttons or a dropdown would be better suited. Personally, I'd say a dropdown is better for you as there's already an editor template built for it, example:
Model:
I have added the following to properties
public string Category { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
In the load method I have put two sample categories in there:
Categories = new List<SelectListItem>
{
new SelectListItem
{
Selected = false,
Text = "Chemistry",
Value = "Chemistry"
},
new SelectListItem
{
Selected = false,
Text = "Science",
Value = "Science"
}
};
View:
#Html.DropDownListFor(m => Model.Category, Model.Categories)

Related

Query Selected Items using checkbox in MVC

I like to ask if how would it be possible that the selected items in the checkbox will be used in making linq query in MVC.
I have this one in my view where in I displayed all the possible options in which the user will just simply select the types of softwares that will be used to generate reports.
#using (Ajax.BeginForm("Create_Report", "Softwares",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "target2"
}))
{
#Html.ValidationSummary(true)
<p>For A Reports: Kindly check softwares to create reports.</p><br />
foreach (var item in Model) {
<input type="checkbox" value="#item.software_name" name="software_type"/>#item.software_name
<br />
}
<input type="submit" value="Create Report"/>
}
After that, I want that the selected software types will be used in the query like for example if the user selects Adobe Pro, Adobe Illustrator, MS Visio, and Acrobat, the query should go like "Select from Software _table where software__type = "Adobe Pro" && software_type ="Adobe Illustrator && "so fort.
Is there any ways to shorten the query using the selected items from the checkbox? Any help is much appreciated.
Assuming your POST method is
[HttpPost]
public ActionResult Create_Report(string[] software_type)
then software_type will contain an array of the selected values so you can use .Contains() to filter the query
var items = db.Software.Where(s => software_type.Contains(s.software_type))
Side note: remove those awful underscores from your properties and follow normal naming conventions (SoftwareType, SoftwareName, etc or simply Type, Name etc since they are already in a class named Software)
You need to define a collection to store you selected items and use model binding to map the selected items to this property.
//store checked Items
public IEnumerable<string> SelectedSoftware { get; set; }
//check box list items
public List<string> SoftwareList = new List<string>();
foreach (var item in Model.SoftwareList )
{
<input type="checkbox" name="SelectedSoftware" value="#item">#item
}
in your controller:
public ActionResult Create_Report(string[] SelectedSoftware)
{
//do action
}

DropDownList how select default value

I have many DropDownLists on page
class BigViewModel
{
public List<SmallViewModel> SmallVM {get;set;}
public List<SelectListItem> Items {get;set;}
//some other properties
}
class SmallViewModel
{
public string ItemId {get;set;}
//some other properties
}
<table>
#for( var i = 0;i<Model.SmallVM.Count();i++)
{
<tr>
<td>
#Html.DropdownListFor(m=> m.SmallVM.ItemId, Model.Items)
</td>
</tr>
}
//display other properties
</table>
in controller
bigViewModel.Items = List<SelectListItem>
{
new SelectListItem{Value = "1", Text = "aaa"},
new SelectListItem{Value = "2", Text = "bbb"},
new SelectListItem{Value = "3", Text = "ccc"},
}
bigViewModel.SmallVM = new List<SmallViewModel>
{
new SmallViewModel{ItemId = 3},
new SmallViewModel{ItemId = 2},
}
In controller I set diffrent ItemId for every SmallVM and each DropDownList uses the same Items collection. I want to set default Value from SmallViewModel for each DropDownList. For example in this case there are two DropDownLists first should display default text "ccc" and second "bbb".
Should I put diffrent List<SelectedListItem> for every SmallViewModel and set them Selected property or there is other way?
This behavior has been reported as a bug on CodePlex but not yet fixed. Using DropDownListFor() in a for loop does not bind correctly and the first option is always selected despite the value of the property. In order for DropDownListFor() to work correctly when using a collection, you need to use an EditorTemplate for the model.
In /Views/Shared/EditorTemplates/SmallViewModel.cshtml
#model SmallViewModel
#Html.DropdownListFor(m => m.ItemId, (SelectList)ViewData["Items"])
Then in the main view
#model BigViewModel
#using(Html.BeginForm())
{
// Pass the select list to the EditorTemplate as addtionalViewData
#Html.EditorFor(m => m.SmallVM, new { Items = Model.Items })
<input type="submit" />
}
You should now have 2 <select> controls displaying "ccc" and "bbb" respectively.
Based on your code updates, I think you just need to modify your view code to:
#Html.DropdownListFor(m=> m.SmallVM[i].ItemId, Model.Items)
However, I have distinct feeling that this is very much an XY problem, and although this change will make everything wire up on post, you're still not going to be getting what you actually need for the true problem you're trying to solve.

How to assign a value to model property once HTML.RadioButtonFor is selected

I am new to MVC. Currently I have a strongly typed view, and I use two Html.RadioButtonFor for labels, the codes are somethings like:
<label class="radio">
#Html.RadioButtonFor(model => model.Incoming, true)IncomingItems</label>
<label class="radio">
#Html.RadioButtonFor(model => model.Incoming, false)OutgoingItems</label>
<input type="hidden" id="isIncomingItem" value = "#Model.Incoming" />
What I want is to set model.Incoming to be true when the first radio button is selected or set it to false, and then I want to use this model property right away in the view( assign this value to "isIncomingItem") before the entire form is submitted to server.
Do you guys have a idea about how I could achieve it. Really appreciated!
Your Incoming property is already filled with the selected value and it will be available for the action method. And if you want to set the same value in the hidden field, try as following
#Html.HiddenFor(m => m.Incoming,new { id = "isIncomingItem"})
You'd have to use jQuery, doing something like:
$("[name='Incoming']").change(function () {
$("#isIncomingItem").val($(this).val());
});

MVC 4 #Html.DropDownListFor() not passing model values to dropdown

I am new to MVC and trying a test application to get my feet wet. Part of this application is to generate a form with a drop down box. I use the
#Html.DropDownListFor() to generate this, and on the create form the drop down works fine. But when I go to the edit form the model value is not passing to the drop down.
SelectList Item
public static string[] OnOffList()
{
var ret = new string[] { "On", "Off" };
return ret;
}
Form code
#Html.DropDownListFor(model => model.ServiceCondition, new SelectList(OnOffDropDownHelper.OnOffList()))
For this instance assume that model.ServiceCondition = "Off".
For some reason whenever I call this form the dropdown value is always "On", it seems to be completely ignoring the model value.
I have also tried this
#Html.DropDownListFor(model => model.ServiceCondition, new SelectList(OnOffDropDownHelper.OnOffList(), "Off"))
to mandate the "Off" value, but it is still coming up as "On" as the selected value in the drop down.
I would like to reiterate, I do know that the model value is "Off", and I created an identical "Create" form using the same #Html.DropDownListFor() and it was able to pass the value to the model just fine.
Like I said, I am new to MVC so any help would be greatly appreciated.
Thanks.
I think you have to set the IsSelected property. This always works for me:
First, just put a property in your model to tidy up the View code:
public List<SelectListItem> OnOffDDL
{
get
{
return OnOffDropDownHelper.OnOffList()
.Select(s => new SelectListItem
{
Text = s,
Value = s,
Selected = ServiceCondition == s
})
.ToList();
}
}
Then do:
#Html.DropDownListFor(model => model.ServiceCondition, model.OnOffDDL)
This may be a little overkill, but is helpful if your model could have different options based on the model itself (even though for now it is just On and Off). Like in the future if certain items could have a "Standby" mode, etc, where you would be getting the actual options from a database for that particular item.
Use a SelectList for the source, so your Model could have:
public List<SelectListItem> OnOffList{ get; set; }
Then populating the Model in your controller like:
model.OnOffList.Add(new SelectListItem()
{
Text = "On",
Value = "On"
});
...etc.
Then you can set the selected item like:
#Html.DropDownListFor(m => m.ServiceCondition, new SelectList(Model.OnOffList(), "Value", "Text", Model.ServiceCondition))
Turns out to be a rookie mistake on my part.
Who ever designed the databese had the field ServiceCondition as nchar(8) leaving white space at the end of the "on ", "Off " values.
A .Trim() in the field in question fixed the issue.
Thanks a ton for the help.

Asp.net mvc3 How to display byte as string? Asp.net mvc3

I have Gender attribute as tiny int in Db for employee. When user create new employee i want him to choose male/female (which is working properly) by clicking on radio button. Everything is working fine (create and edit) but i want to display in form (for index, details and delete) not 1 or 2, but male/female. there should be some if statement in view but i'm not sure where to put it or how to write correct one ...
any idea?
Thanks!
this is part of code from model:
This one is from details.cshtml:
If you want to avoid having extra properties on your model or adding stuff to your viewbag you can write it inline using razor syntax like below..
<div class="display-field">
#if (model.GENDER == 0){ #Html.Raw("Male") }
#else if (model.GENDER == 1){ #Html.Raw("Female") }
</div>
That's off the top of my head so you might need to check the exact syntax but i think that's close. It will also just dump "Male" or "Female" inside the div, you might want to put it in a label or p tag at least.
This however isn't the approach I would use in a production app, throughout the code i would use a gender enum to give meaning to your bit value and extend enum to include a description that you can parse for presentation purposes.
I think from what u have said u can write it inline using the razor syntax like below in ur details.cshtml
<div class="display-field">
#if(model.GENDER ==0)
{
<label>Male</label>
}
else if(model.Gender==1)
{
<label>Female</label>
}
</div>
I think this must be enough for displaying the Gender in details page.plz comment if u need any help
Use a condition ? true : false selector
int gender = 1; // assumed male
String genderDesc = (gender == 1) ? "Male" : "Female";
You Could Make this a Drop Down field? In your controller do:
ViewBag.Gender = new[]
{
new SelectListItem { Text = "Male", Value = "1" },
new SelectListItem { Text = "Female", Value = "2" }
}.WithEmpty();
The WithEmpty() will give you a blank option or without it will select the top one.
#Html.DropDownListFor(m=> m.Gender, (Ienumarable<SelectListItem>)ViewBag.Gender);
This way the user will see Male and Female but the value will be bound to your model using the value which is 1 or 2.
I'd advise that you create a ViewModel class to represent the Employee entity in a View-friendly format decoupled from your database model and present it in a strongly typed view so you can return it from the controller.
Hint: Have the Gender property represented as a string in the ViewModel and do the conversion from byte to the string representation in your controller
You may put the code in your controller as e.g:
public ActionResult EmployeeDetails(int id)
{
//retrieve the entity from the DB
//set other employee properties here.
//I'm assuming you have set males to 2 and females to 1
...
employeeViewObject.Gender = employeeObjectFromDB.Gender.Value==2?"Male":"Female";
return View(employeeObjectFromDB);
}
Your strongly typed view will not have trouble displaying the gender while saving you the dirt of mixing code and mark-up as:
<p>model.Gender</p>
or
Html.DisplayFor(model=>model.Gender)

Categories

Resources