I am using Twitter Bootstrap in an ASP.NET MVC application. In one page I want to show a Grid or List view when a user click on the relevant icon. To do that, I'm using radio buttons and it does show based on user selection.
But the problem is that it always focuses on the Grid icon, even if it fires list mode.
Here's My Code:
<div class="row" >
<div class="col-xs-4 col-sm-4">
<form class="pull-left">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active" title="Show as a Grid" >
<i class="fa fa-table"></i>
#Html.RadioButtonFor(model => Model.Context.ViewMode, "grid",
new { name = "viewmode", #class = "",
onchange = "setLocation('?viewmode=grid');" })
Grid
</label>
<label class="btn btn-primary" title="Show as a List" >
<i class="fa fa-list"></i>
#Html.RadioButtonFor(model => Model.PagingFilteringContext.ViewMode, "list",
new { name = "viewmode", #class = "",
onchange = "setLocation('?viewmode=list');" })
List
</label>
</div>
</form>
</div>
</div>
<div class="show-content">
#if (Model.Context.ViewMode == "grid")
{
<label>Grid content here...</label>
}
else
{
<label>List content here...</label>
}
</div>
// set visibility between icons
$(document).ready(function () {
$("#Context_ViewMode").on('click', function () {
ToggleRadioButtons("#Context_ViewMode", $(this));
});
});
function ToggleRadioButtons(groupName, current) {
var chk = $(groupName + " .fa-table");
$(chk).removeClass('fa-table').addClass('fa-list');
$(current).find(">:first-child").removeClass('fa-list');
$(current).find(">:first-child").addClass('fa-table');
}
But it didn't set focus on List icon when clicked. Any ideas?
Edit:
I managed to get event firing work, but it doesn’t stay as selected if ‘List’ selected, change back to ‘Grid’ highlighted(active) after loading correct ‘List’ result from the server.
Summary of changes:
Added new class ‘fawsm-radiobutton’ for both labels
Added new class ‘nonactive’ for label list
Changed the JavaScript to add remove 'active' and 'notactive'
Here’s My Code changes:
<label class="fawsm-radiobutton btn btn-primary active" title="Show as a Grid" >
<i class="fa fa-table"></i>
#Html.RadioButtonFor(model => Model.Context.ViewMode, "grid",
new { name = "viewmode", #class = "",
onchange = "setLocation('?viewmode=grid');" })
Grid
</label>
<label class="fawsm-radiobutton btn btn-primary notactive" title="Show as a List" >
<i class="fa fa-list"></i>
#Html.RadioButtonFor(model => Model.PagingFilteringContext.ViewMode, "list",
new { name = "viewmode", #class = "",
onchange = "setLocation('?viewmode=list');" })
List
</label>
$(document).ready(function () {
$("#Context_ViewMode>.fawsm-radiobutton").on('change', function () {
ToggleRadioButtons("#Context_ViewMode", $(this));
});
});
function ToggleRadioButtons(groupName, current) {
var chk = $(groupName + " .fawsm-radiobutton.active");
$(chk).removeClass('active’).addClass('notactive');
$(current).find(">:first-child").removeClass('notactive');
$(current).find(">:first-child").addClass('active');
}
When I use developer tool(F12) on the browser it shows the removal and addition of ‘active’ and ‘notactive’ classes to lable. But after loading List items from the server it revert back to original ‘Grid’ icon in active mode.
So I guess that when the browser renders
#if (Model.Context.ViewMode == "grid")
{}
else{}
section I need to notify client to do the above changes to the label classes. I do not know how to do it. Do I need to use something like AJAX?
You should use the .focus() method.
Related
I have no idea how to do something like this.
I have a dropdown with six element, and button.
When I click butto I want to show bootstrap modalpopup. It's a simple.
But I want to tt depends on the selection drop down.
My view:
<button type="button" class="btn btn-default" data-toggle="modal" data-target=".bs-example-modal-lg-addCompanyRisk">
<i class="fa fa-plus"></i> Add
</button>
<div class="modal fade bs-example-modal-lg-addCompanyRisk" tabindex="-1" role="dialog" aria-hidden="true" id="allCustomerModal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
[... Load index from other view...]
<div class="modal-body">
<button type="submit" class="btn btn-default" data-dismiss="modal">#Resources.Common.Cancel</button>
</div>
</div>
</div>
</div>
the content of the list which is to settle on a modal should be dependent on the dropdown.
If the backet all form and button (class="btn btn-default") is a submit, then I dont know how show modal from ActionResult(controller)
EDIT
Partially I solved my problem.
I add to dropdown Ajax.BeginForm and submit
#using (Ajax.BeginForm("GetAllRiskForCompanu", "InsuranceCompanyRisks", null, new AjaxOptions
{
HttpMethod = "Post",
}))
{
#Html.AntiForgeryToken()
#Html.DropDownListFor(model => model.InsuranceCompanyId, ViewBag.InsuranceCompany as SelectList, #Resources.Common.Select, new { #class = "form-control", #required = "required", onchange = "$(this.form).submit();" })
#Html.ValidationMessageFor(model => model.InsuranceCompanyId, "", new { #class = "text-danger" })
}
on controller write method:
[HttpPost]
public Void GetAllRiskForCompanu(FormCollection form)
{
int? companyId = form["InsuranceCompanyId"].GetNullableInt();
if (companyId.HasValue)
{
//set session varible
InsurancePolicySession.InsuranceCompanyRisks = icrf.GetAll(companyId.Value);
}
}
by button add I show modala with render partialView
#Html.Partial("~/Views/InsurancePolicyItem/IndexPolicyCompanyRisk.cshtml", #InsurancePolicySession.InsuranceCompanyRisks)
when I change dropdown selected value the session refresh but when I show modal still view old value.
Rather than mess around with an AjaxForm and directly manipulating a Bootstrap modal, you might find it easier to use something like Bootbox, which will generate your Bootstrap modal as needed.
I would use a normal form:
#using(Html.BeginForm("action", "controller", FormMethod.Post, new { id="some-id", role="form" }))
{
#Html.DropDownListFor(m => m.SomeId, Model.Somethings, new { #class="form-control" })
<button type="submit" class="btn btn-default">Submit</button>
}
Then, capture the form submission and do an Ajax request to get your content:
$(function(){
$('#some-id').on('submit', function(e){
e.preventDefault(); // prevent normal form submit
var form = $(this);
var data = form.serialize();
$.post(form.attr('action'), data)
.done(function(response, status, jqxhr){
// handle response...
})
})
})
Inside the success handler (.done()), build up your dialog. Bootbox has built-in functions for alert, confirm, and prompt (it's primary purpose is to mostly replicate those native functions), but you'll probably want to use dialog(), which lets you completely customize the modal. You'll want to read the documentation to get the most out of it, but a basic usage could be (starting from where you see // handle response... above):
var dialog = bootbox.dialog({
title: 'Some Title',
message: response,
buttons: {
cancel: {
label: 'Cancel',
className: 'btn-default',
callback: function(){
dialog.modal('hide');
}
},
save: {
label: 'Submit',
className: 'btn-primary',
callback: function(){
// submit your data from the injected content, somehow...
}
}
}
});
I primarily use Bootbox at this point, simply because I find it easier than having the modal template on the page. I've also run into the same issue you seem to be having, which is that a reused modal doesn't seem to want to update it's content.
Disclaimer: I am currently a collaborator on the Bootbox project, although I am mostly there to keep the documentation up to date and triage issues.
I have this code:
<div class="col-xs-6 col-sm-3">
#Html.DropDownList("cssFiles", (IEnumerable<SelectListItem>)ViewBag.cssFiles, "Crear Nuevo", new { #class = "form-control", #id = "selCssFile" })
<span>
<input type="text" class="form-control" id="txtFileName" style="display:none;" placeholder="Nombre del archivo">
</span>
</div>
I want to add a Javascript event for show the "txtFileName" when "Crear Nuevo" is select, and hide it when the dropdown change
Basically you need to attach click event on your dropdown element.
Code
$('#selCssFile').on('change',function(){
//implement code after selected the option
});
UPDATE:
Here is my .html page looks like and withing the form tag I have couple of buttons (page size, save to db, remote items)
<div class="col-lg-12">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">Records</h3>
</div>
#using (Html.BeginForm("Index", "MyController", FormMethod.Post, new { #id = "form_header" }))
{
<div class="panel-body">
<div class="row">
<div class="col-xs-4">
<div class="form-group">
<label for="" class="col-xs-5 control-label">Rows per page:</label>
<div class="col-xs-4">
#Html.DropDownListFor(m => m.PageSize,
new List<SelectListItem>
{
new SelectListItem() { Text = "10", Value = "10" },
new SelectListItem() { Text = "25", Value = "25" },
new SelectListItem() { Text = "50", Value = "50" },
new SelectListItem() { Text = "ALL", Value = "ALL" }
}, new { #class = "form-control", Name = "pageSizeDDL" })
</div>
</div>
</div>
<div class="row text-right">
<div class="col-xs-12">
<button class="btn btn-success" type="submit" id="btnSavetoDB" name="saveToDB" value="Save to DB">
<span> <i class="fa fa-save"></i> Save to Database </span>
</button>
<button class="btn btn-danger" type="submit" id="btnRemoveFromGrid" name="removeItems" value="Remove Item From Grid">
<span> <i class="fa fa-remove"></i> Remove </span>
</button>
</div>
</div>
</div>
<div class="col-lg-14">
<div class="panel-body">
<div class="row">
<div class="test" style="overflow: scroll; width: 100%">
<div style="width: 1000px">
#if (Model != null)
{
//grid
}
</div>
</div>
</div>
</div>
</div>
</div>
}
</div>
I have seen all sorts of approach but still not convinced the best way to handle and in my situation I have multiple buttons or events that fire based on the user action: for an example in my case:
in the form:
I have page size dropdown where user can select number of rows to display
I have a import button to import the doc
I have save button - save to db
I have a remove button - remove from grid
currently this is how I have laid out:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file, FormCollection formCollection, string pageSizeDDL, string saveToDB, string removeItems, string PageList)
{
if (file upload) {....}
if (formCollection) { .... }
if (pageSizeDDl {....}
..........
}
my question is:
What if i need the form values for all buttons or perhaps is that right approach the way I'm doing?
I have seen wrapping each button in it's own form in view which I things its not the correct approach and the reason is if I have 10 button in a single page does it mean I have to have 10 form?
Below is code that is supposed to make a text box appear/disappear based on whether or not a box is checked (the text box is hidden when the page loads). All the alerts are firing properly, however I cannot get the check box to .show() function to work.
Here is the jQuery. This from inside the document.ready function. You can see from what I've commented out the other two methods I've tried (neither worked).
$('#OverrideRegionInd').click(function () {
alert($(this).is(':checked'));
if ($(this).is(':checked')) {
alert("inside if");
$('#Region').show();
//$('#Region').css("display", "inline");
// $('#Region').toggle();
$('#territoryName').html("");
$('#Region').val("");
} else {
alert("inside else");
$('#Region').hide();
//$('#Region').css("display", "none");
// $('#Region').toggle();
}
});
Here is the code from the view
<div class="M-editor-label">
#Html.LabelFor(model => model.Region)
</div>
<div class="M-editor-field" id="territoryName">
#Html.TextBoxFor(model => model.Region, new { style = "display: none;" })
#Html.ValidationMessageFor(model => model.Region)
</div>
Here is the HTML once the page is rendered for this particular set of <div>'s
<div class="M-editor-label">
<label for="Region">Territory</label>
</div>
<div class="M-editor-field" id="territoryName">
<input id="Region" name="Region" style="display: none;" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Region" data-valmsg-replace="true"></span>
</div>
That's because you're setting:
$('#territoryName').html("");
That's the parent of #Region, you're effectively removing the #Region element with that line. Take that out and it'll work fine.
DEMO
I'm searching for a good way to bind a List<string> to a form in MVC3. Right now I have 2 options:
Use a ListBox with a textbox, add/delete button in jquery and do a select all items before posting my form
Use a <li> that will contains a <input type="hidden" /> with the value also with a add/delete button in jquery
I'm sure there is easyer way to do this but I did not found anything here so I'm asking for help. My concern is to add different bussiness units (string) to a company while editing the company other properties (name, address..).
Thanks!
Using a ListBox seems like a good way to achieve that. Then you could have a textbox and an add button next to it that will append a new element to the listbox and a delete button that will remove the selected items from the ListBox all using client side jquery. And when the form is submitted, since you have used a ListBox (<select> with multiple="multiple") it will automatically bind to a property on your view model of type List<string> and you will be able to fetch the selected values.
Here's my code for the first option, if anyone find a better solution, let me know!
Html/Razor :
<div class="row">
<div class="span12">
<div class="control-group">
<label for="AddBusinessUnit" class="control-label">#Strings.BusinessUnit</label>
<div class="controls">
<div class="input-append">
<input type="text" class="span2" size="16" id="AddBusinessUnit" />
<button class="btn" type="button" id="add-business-unit">#Strings.Add</button>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
#Html.ListBoxFor(model => model.BusinessUnits, SelectLists.BusinessUnits(Model.BusinessUnits, false), new { Multiple = "multiple" })<br/>
#Strings.DeleteSelectedElement
</div>
</div>
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="#Strings.Save" />
#Strings.Cancel
</div>
Js :
<script type="text/javascript">
$(document).ready(function () {
$('#add-business-unit').click(function (e) {
var bu = $('#AddBusinessUnit').val();
if (bu != '') {
$('#BusinessUnits').append($('<option></option>').val(bu).html(bu));
$('#AddBusinessUnit').val('');
}
e.preventDefault();
});
$('#delete-business-unit').click(function (e) {
$('#BusinessUnits :selected').remove();
e.preventDefault();
});
$('input[type="submit"]').click(function () {
$('#BusinessUnits option').attr('selected', 'selected');
});
});
The SelectList :
public static class SelectLists
{
public static IList<SelectListItem> BusinessUnits(IList<string> bussinessUnits, bool addEmpty, string selected = "")
{
var list = new List<SelectListItem>();
if(addEmpty) list.Add(new SelectListItem());
list.AddRange(bussinessUnits.Select(businessUnit => new SelectListItem {Selected = selected == businessUnit, Text = businessUnit, Value = businessUnit}));
return list;
}
}
It will bind to my property public virtual IList<string> BusinessUnits { get; set; } in my model.
Hope it can helps!