MVC RadioButtonFor - asp.net-mvc

I have something along the following:
<div class="editor-field">
#Html.RadioButtonFor(m => m.TotalCol, "Yes") #Html.Label("Yes")
#Html.RadioButtonFor(m => m.TotalCol, "No") #Html.Label("No")
Note that TotalCol is a string.
public string TotalCol { get; set; }
I use the following to get the value:
var TotalCo = $('#TotalCol').val();
alert(TotalCo);
the alert show Yes.
If I do an alert on submit of the form without selecting either the Yes or No, I still
get Yes. Why is that. Why doesn't it just return blank.
Thanks in advance

From looking at you code I see that your RadioButtons are actually "grouped" together as #TotalCol and therefore the jquery can only grap the first element and display for you the val from that particular element of the group. For instance if you were to reverse this you would get the opposite result (alert would return "No" like this):
#Html.RadioButtonFor(m => m.TotalCol, "No") #Html.Label("No")
#Html.RadioButtonFor(m => m.TotalCol, "Yes") #Html.Label("Yes")
I hope this is making any sense :)

When you have two radio buttons with the same name (or ID) you need to find out which one was selected. You can do that by using the selector :checked.
Example:
$('#TotalCol:checked').val();
or
$('input[name=TotalCol]:checked').val();

Related

Replacing a form text field with drop-down list

I created a simple Tasks webapp using .NET 4.0 MVC & Entity Framework. Pulling data from a database.
I have tables:
Staff {PkId, FirstName, LastName}
Tasks {PkId, Task, TaskDescription, DueDate}
TasksAssigned {PkId, StaffId, TaskId}
When I go to Edit TasksAssigned record (Edit page) I'll get a form (stripped div/css for space)
#Html.LabelFor(model => model.PkId)
#Html.EditorFor(model => model.PkId)
#Html.LabelFor(model => model.StaffId)
#Html.EditorFor(model => model.StaffId)
#Html.LabelFor(model => model.TaskId)
#Html.EditorFor(model => model.TaskId)
But I need to be shown Task instead TaskId, and LastName instead StaffId. And I need is to have drop-downs in the form instead text field with all names and all tasks available so I can select other person or other task (or both).
I'm assuming I should use DropDownList() or DropDownListFor() ?
Thanks for any help.
(addon)
Let me try to explain better...
So, let's say there are Staff members:
{ 12, "John", "Dow" },
{ 15, "Bill", "Smith" }.
Let's say there is task
{ 3, "Clean the printer", "Call company to clean the printer... ", "2016-06-25" }.
So, there's going to be a record in TaskAssigned
{ 8, 12, 3 }
Ok?
Let's change the the record so the task is assigned to Bill instead John. So, I would click on "Edit" button and on the Edit page I would have form with two text fields ( [ and ] represent text field of the form)
Staff: John Dow
Task: Clean the printer
To change it I have to replace the name with 15, Bill's ID, right? I would like to have a drop-down with names of John and Bill and then select Bill's name and when submit, Bill's ID will be stored in TasksAssigned table.
I'm assuming you're including the other two tables when you call for your data. If so you should easily be able to display the fields you're needing with referencing towards the correct ones. Purely based on what's in your question this should look something like the below.
#Html.HiddenFor(model => model.TaskId)
#Html.LabelFor(model => model.Tasks.Task)
#Html.EditorFor(model => model.Tasks.Task)
#Html.LabelFor(model => model.Staff.LastName)
#Html.EditorFor(model => model.Staff.LastName)
I don't see the immediate need to show or even give an option to edit the PK value of the TaskAssigned entry. That's the reason I moved it to Hidden
If you want to give the users a dropdownlist you'll have to make sure you're sending the potential choices along in your Model. In this case you'll preferably want to be using a ViewModel to send along the choices.
That way you'll be able to do something like the below.
List<SelectListItem> listOfStaff = new List<SelectListItem>();
listOfStaff.Add(new SelectListItem
{
Text = "Mark",
Value = "1"
});
listOfStaff.Add(new SelectListItem
{
Text = "John",
Value = "2",
Selected = true
});
Leading you to the DropDownListFor you already referenced in your question.
#Html.DropDownListFor(model => model.StaffId, model.listOfStaff, "-- Select Staffmember --")
Hope this helps you along a little more towards a working solution.

How to FluentBootstrap validation in MVC

Is it possible to use validation messages in FluentBootstrap on form element level?
When I use:
#using (var form = Html.Bootstrap().Form().Begin())
{
#form.InputFor(m => m.Name)
#form.Submit()
}
There is no validation, except validation error class on input tag. I want to show validation message for Name property and has-error class on form-group container.
Just add #form.ValidationSummary() where you want the general validation summary to appear. There is an example of this as well as some other examples here: https://github.com/daveaglick/FluentBootstrap/blob/develop/FluentBootstrap.Tests.Web/Views/MvcTests/MvcForms.cshtml
If there is no particular reason to use InpuFor you can do the following.
#form.EditorFor(m => m.Name, addValidationMessage: true)
This will show what error message you put on your Name property's attribute.
Such as
[StringLength(50, ErrorMessage="Cannot be longer than 50 character.")]
public string Name { get; set; }
I personally use the base validation helper
#form.InputFor(m => m.Password, FormInputType.Password)
#Html.ValidationMessageFor(m => m.Password)
I can set the type of the input unlike the case when I use EditorFor

kendo mvc grid editor template with checkbox list

I have Kendo MVC Grid with Popup Editor template.
I need to add Checkbox list for a model property. This is what I am doing
I declared a property in my view model like this...
public List<string> Category { get; set; }
This is how I am declaring Checkboxes in view
<ul>
#foreach (var g in (MultiSelectList)ViewData["BondPermitTypes"]) {
<li class="checkbox">
<label>
<input type="checkbox" name="Category" class="checkbox-removekvalid" id="Category_#g.Value" value="#g.Value.ToString()" />#g.Text
</label>
</li>
}
</ul>
This code is working fine when I edit the existing records...
The problem is when I try to create new record and select any checkbox, all of the checkboxes are getting checked
Moreover, even if I hack around using jquery and force it to check only selected checkboxes then when I post back the "Category" property has only one string all the time, which is "true".
I appreciate your help!
Sorry for the late reply...
To make it work, I have added the default value for the Category property in the Kendo Grid. Like this
.Model(model =>
{
model.Id(p => p.PkProperty);
model.Field(p => p.Category).DefaultValue(new List<string>());
})
Hope it helps you! :-)

MVC models to populate KendoUI Multiselect - preloading selected items

I currently have the multiselect working the way I want it with one exception. Preloading previously selected items.
My view looks:
<div class="editor-field">
#Html.LabelFor(model => model.UntaggedPersons)
#Html.ListBoxFor(model => model.PeopleToTag,
new SelectList(Model.CommitteeMembers, "PersonId", "FullName"))
</div>
JS:
$("#PeopleToTag").kendoMultiSelect({ "dataTextField": "FullName", "dataValueField": "PersonId", "placeholder": "Tag or Untag Persons to Action Item" });
PeopleToTag is an IEnumerable<int> int that posts to the controller
CommitteeMembers consists of a persons First, Last, FullName, and PersonId
This works perfectly, I can manipulate who is tagged in the post to the controller.
Now I want to add the functionality of preselecting those that are currently tagged.
How do I add a preselected Value? I have a model with:
model.TaggedPersons consists of a persons First, Last, Fullname, PersonId.
How do I wire up the javascript to display the model.TaggedPersons as the already selected value?
I don't mind using the MVC wrapper approach if it is easier.
I've tried something like:
<div class="editor-field">
#Html.LabelFor(model => model.TaggedPersons)
#(Html.Kendo().MultiSelectFor(model => model.PeopleToTag)
.Name("PeopleToTag")
.Placeholder("These people are Tagged")
.DataTextField("FullName")
.DataValueField("PersonId")
.BindTo(Model.CommitteeMembers)
.Value(Model.TaggedPersons)
)
</div>
However this isn't even rendering a kendo multiselect for me at present. That's the general thought of how I want to approach it though.
Any help is much appreciated!
Change:
DataTextField("FullName") to DataTextField("Text")
DataValueField("PersonId") to DataValueField("Value")
SelectList uses "Text" and "Value", respectively. You already filled the fields of the select list with FullName and PersonId when the selectlist was created.

Same property in two different tabs (divs). Property is null when tab 2 is posted to action method

When I post back to the server when tab2 is active viewModel.FirstName is null in the action method. How do you tell the modelbinder that it should take #Html.EditorFor(m => m.FirstName) from tab2 when that tab is active? Everything works fine for tab1.
jQuery hide() and show() are used for switching between tabs.
Controller
[HttpPost]
public ActionResult Index(MyViewModel viewModel)
View
<div id="tab1">
#Html.EditorFor(m => m.FirstName)
</div>
<div id="tab2">
#Html.EditorFor(m => m.FirstName)
</div>
It sounds like you have both FirstName input fields inside the same form.
Something like:
<form>
<div id="tab1">
#Html.EditorFor(m => m.FirstName)
</div>
<div id="tab2">
#Html.EditorFor(m => m.FirstName)
</div>
</form>
When you post this, the form is submitted as:
FirstName=valueFromField01&FirstName=valueFromField02
From the behavior you are describing, it seems that once the model binder sets the FirstName field in your MyViewModel, it ignores the second one (but I'm not really sure about that).
Solutions:
Rather than have a form with different tabs inside of it, have a form inside each tab. This will ensure you only have one FirstName inside a form.
Update the model so that you get both fields. You would need to use an array of string: string[] FirstName.
Update:
Instead of updating your ViewModel, it might be easier to simply add another parameter to your action method so you can get both FirstName values and then figure out which one was actually provided:
public ActionResult Index(MyViewModel viewModel, string [] FirstName).
Then you can have logic in your action method to set the FirstName in your viewModel:
if(!string.IsNullOrEmpty(FirstName[0]))
{
viewModel.FirstName = FirstName[0]
}
else if(!string.IsNullOrEmpty(FirstName[1]))
{
viewModel.FirstName = FirstName[1];
}
You could achieve that disabling the duplicated name form elements. By default, disabled form elemnts will not be passed to the request, and your Controller problably will receive the name corectly from the tab2 when it is shown active.
So. here follows one example
$('#tab1')
.hide()
.find('input[name="FirstName]"')
.prop('disabled',true);
$('#tab2').show()
.find('input[name="FirstName]"')
.prop('disabled',false);
Latter I suggest you should wrap this behaviour inside a function.
Hope it helps.

Resources