Bootstrap multi select buttons - c#

In previously I use standard check-boxes, but now I want to use the bootstrap Multiple select boxes.
At this moment I can't see any rows in my drop down.
My new code:
<li>
<select href="#" class="selectpicker" data-value="option1" tabIndex="-1" multiple data-selected-text-format="count">
<option checked> #Html.DisplayTextFor(model => Model.AvailableCompanies[i].NAME)</option>
<option name="selection[#i]" value="true"></option>
<option name="ids[#i]" value="#Model.AvailableCompanies[i].ID"></option>
</select></li>
My previously code:
<li>
<a href="#" class="small" data-value="option1" tabIndex="-1">
<input type="checkbox" checked /> #Html.DisplayTextFor(model => Model.AvailableCompanies[i].NAME)
<input type="hidden" name="selection[#i]" value="true"/>
<input type="hidden" name="ids[#i]" value="#Model.AvailableCompanies[i].ID" />
</a>

In C# we have cool helper and Multi select buttons
#Html.ListBoxFor(model => model.Companies,
new MultiSelectList(Model.AvailableCompanies, "ID", "NAME", null),
new
{
data_dropdown_align_right = "auto",
id = "",
data_selected_text_format = "count",
data_actions_box = "true",
#class = "selectpicker form-control",
multiple = "multiple",
data_live_search = "true"
})

Related

Multiple forms on one MVC form, model data does not pass to Action

I am creating a loop of objects/forms that will enable a user to update data for each object in a partial view. The unique data properly displays in the loop of forms but when I try to submit to the action, the model data that passes to the action is blank and doesn't pull the data from the form I'm submitting from.
In debugging, object data is successfully passed to each var item in the loop.
#foreach (var item in ViewData["CtaList"] as
IEnumerable)
Ex. There are 5 individual forms that are created by the loop each with their own Save and Delete button. If I click Save on the 3rd form in the loop, it goes to the action but the MedInfoModel model for that individual object is blank.
View
#{
ViewData["Title"] = "Edit";
ViewData["hidePluginCSS"] = "yes";
#model POR.Common.MedInfoModel;
}
#foreach (var item in ViewData["CtaList"] as IEnumerable<POR.Common.CtaListModel>)
{
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Edit CTA</h3>
</div>
<div id="partialPlaceHolder">
#using (Html.BeginForm("SaveCtaInfo/" + item.CtaId, "Med", FormMethod.Post, new { #Id = item.CtaId, #class = "content-form form-horizontal" }))
{
<div class="panel-body">
<form class="content-form form-horizontal">
<div class="form-group justify-content-end">
<label for="inputEmail" autocomplete="false" class="col-md-9 control-label">Select Type</label>
#Html.DropDownListFor(m => item.CtaType, Model.CTATypeDropdown, new { #class = "form-control"})
</div>
<div class="form-group justify-content-end">
<label for="inputEmail" autocomplete="false" class="col-md-9 control-label">Select Priority</label>
#Html.DropDownListFor(m => item.CtaOrder, Model.CTAOrderDropdown, new { #class = "form-control" })
</div>
<div class="row mt-2">
<div class="col-md-12 r">
<button class="btn btn-raised btn-danger r" name="ctaSave" value="ctaDelete">Delete</button>
<button class="btn btn-raised btn-success r" name="ctaSave" value="ctaSave">Save</button>
</div>
</div>
</form>
</div>
}
</div>
</div>
}
Controller:
[HttpPost]
public ActionResult SaveCtaInfo(MedInfoModel model, int id)
{
string _sSubmit = Request.Form["ctaSave"].ToString();
if (_sSubmit == "ctaSave")
{
// Code for cta save
model.CtaActionType = "UPDATE";
Helper.SQLSPCrudModel(ConnectionString, "storedProcedure", model);
}
else if (_sSubmit == "ctaDelete")
{
// code for cta delete
model.CtaActionType = "DELETE";
Helper.SQLSPCrudModel(ConnectionString, "storedProcedure", model);
}
return RedirectToAction("Edit/" + id);
}
Rendered Form HTML:
<form action="/Med/SaveCtaInfo%2F1000" class="content-form form-horizontal" id="1000" method="post"> <div class="panel-body">
<div class="form-group justify-content-end">
<label for="inputEmail" autocomplete="false" class="col-md-9 control-label">Select Type</label>
<select class="form-control" id="item_0__CtaType" name="item[0].CtaType"><option value="PDF">PDF</option>
<option selected="selected" value="Call">Call</option>
<option value="Menu">Menu</option>
<option value="Video">Video</option>
</select>
</div>
<div class="form-group justify-content-end">
<label for="inputEmail" autocomplete="false" class="col-md-9 control-label">Select Priority</label>
<select class="form-control" data-val="true" data-val-required="The CtaOrder field is required." id="item_0__CtaOrder" name="item[0].CtaOrder"><option value="0">0</option>
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</div>
<div class="row mt-2">
<div class="col-md-12 r">
<button class="btn btn-raised btn-danger r" name="ctaSave" value="ctaDelete">Delete</button>
<button class="btn btn-raised btn-success r" name="ctaSave" value="ctaSave">Save<div class="ripple-container"></div></button>
</div>
</div>
</div></form>
EDIT:
I just noticed however that the form data is passing through via chrome dev tools as:
item[0].CtaType: Call
item[0].CtaOrder: 1
item[0].CtaLink:
Where in a succesfull passing of the model in another action is passing through as:
CtaType: Call
CtaOrder: 1
CtaLink:
Does the action need to be set up differently since it is no longer the parent model of the page?
The answer was to simply replace the following in the controller in original code I posted:
public ActionResult SaveCtaInfo(MedInfoModel model, int id)
with
public ActionResult SaveCtaInfo(MedInfoModel item, int id)
Thanks for your help mxmissile. Sorry for wasting your time.

Submit form over a select element in ASP.Net MVC

So in my file i have this working example of submitting a form and initiating a controller action. And in this form there is a functioning select element and it works as expected, the controller is able to retrieve the value in the select element.
#using (Html.BeginForm("InsertEntry", "Modeliai"))
{
<div class="row">
<div class="col-7">
<input type="text" class="form-control" placeholder="Pavadinimas" name="Pavadinimas">
</div>
<div class="col-3">
<select class="selectpicker" data-live-search="true" name="fk_MARKEid">
#foreach (var item in Model.Markes)
{
<option data-tokens="#item.pavadinimas" data-content="#item.pavadinimas">#item.id</option>
}
</select>
</div>
<button type="submit" class="btn btn-success">Add</button>
</div>
}
But when i try to add select element in the table row, controller somehow doesn't catch the value of the select element.
#using (Html.BeginForm("UpdateEntry", "Modeliai"))
{
<td>
<input type="hidden" name="id" value="#item.id" />
<input type="text" name="pavadinimas" class="form-control" value="#item.pavadinimas" />
</td>
<td>
<select class="selectpicker" data-live-search="true" name="fk_MARKEid">
#{
var ignore = Model.Markes.FirstOrDefault(x => x.id == item.fk_MARKEid);
}
#foreach (var x in Model.Markes)
{
if (ignore?.id == x.id)
{
<option data-tokens="#ignore?.pavadinimas" data-content="#ignore?.pavadinimas" selected="selected">#ignore?.id</option>
}
<option data-tokens="#x.pavadinimas" data-content="#x.pavadinimas">#x.id</option>
}
</select>
</td>
<td style="width: 100px">
<button class="close" type="submit">
<i class="fas fa-pencil-alt" style="font-size: smaller"></i>
</button>
</td>
}
Yes i tried checking if select element names and model names match.
Any help regarding making the second form work or explanation why does this happen would be appreciated
The better way to use select in ASP.Net MVC is to use #Html.DropDownListFor with SelectList.
Example: View
#Html.DropDownListFor(x => x.YourModel, new SelectList(ViewBag.customValue, "Text", "Value"), new { htmlAttributes = new { #class = "form-control" } })
Example: Controller
List<SelectListItem> listForSelect = new List<SelectListItem>();
listForSelect.Add(new SelectListItem { Text = "Your text", Value = "Your value" });
ViewBag.customValue = listForSelect;

MVC multiple different submit buttons? what is the best approach?

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?

Get value from select tag inside form MVC

My HTML (inside a Form):
#using (Ajax.BeginForm("ShowDetail", "Calculation", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "CalcDetail",
LoadingElementId = "Loader",
}))
{
<div class="calculateBox">
<label for="calcOption">Choose value to calculate:</label>
<select form="FormCalcInput" id="calcOption" title="Choose what value you want to calculate">
<option value="anPMT">Payment (PMT)</option>
<option value="anI">Interest (I)</option>
<option value="anFV">Future value (FV)</option>
<option value="anPV">Present value (PV)</option>
</select>
</div>
<div class="calculateBox" background-color="#777777">
#Html.Label("Present value (PV)")
#Html.TextBox("PresentValue")
#Html.Label("Future value")
#Html.TextBox("FutureValue")
#Html.Label("Interest rate")
#Html.TextBox("InterestRate") <br />
<input type="radio" name="advanceOrArrears" id="inAdvance" value="inAdvance" /> In advance<br />
<input type="radio" name="advanceOrArrears" id="inArrears" value="inArrears" /> In arrears
</div>
<div class="calculateBox">
<label for="startDate">Start date:</label>
<input type="date" id="StartDate" name="startdate" title="Choose start date for your calculation" /><br />
#Html.Label("Payment frequency")
<select form="FormCalcInput" id="PmtFreq" name="pmtFreq" title="Choose the payment frequency, for example: Every month">
<option value="Monthly">Monthly</option>
<option value="Quarterly">Quarterly</option>
<option value="Yearly">Yearly</option>
</select><br /><br />
#Html.Label("No of payment periods")
#Html.TextBox("PaymentPeriods")
#Html.Label("Date time convention")
<select form="FormCalcInput" id="anDTC" title="Choose your Date time convention">
<option value="360360">360/360</option>
<option value="365365">365/365</option>
</select><br /><br />
<input type="submit" id="CalcBtn" class="calcBtn" name="SubmitBtn" value="Calculate" title="Calculate your calculation" />
</div>
}
And in my controller:
[HttpPost]
public ActionResult ShowDetail(FormCollection form)
{
var PmtFreq = form["pmtFreq"];
}
Why is the variable in my controller not containing the selected value in my combobox?
I have tried using a #Html.DropDownList but thought this was easier..
I have tested the code and problem is form="FormCalcInput" attribute for select, just remove this. That should solve your problem.
<select id="PmtFreq" name="pmtFreq" title="Choose the payment frequency, for example: Every month">
<option value="Monthly">Monthly</option>
<option value="Quarterly">Quarterly</option>
<option value="Yearly">Yearly</option>
</select>
Add form id FormCalcInput in Ajax.BeginForm
#using (Ajax.BeginForm("ShowDetail", "Calculation",
new AjaxOptions {
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "CalcDetail",LoadingElementId = "Loader" },
new { id ="FormCalcInput" })) // add from id
{
}
Try using data-bound value in your action method:
public ActionResult ShowDetail(string pmtFreq)
{
// ...
}
If you want to capture the data from your form, my suggestion would be to use a strongly typed viewmodel.
For example:
public class MyViewModel() {
public string pmtFreq {get; set;}
/* add more properties for each html input */
}
Then on your controller:
[HttpPost]
public ActionResult ShowDetail(MyViewModel model)
{
var PmtFreq = model.pmtFreq;
}
On your view add at the top a declaration for the viewmodel.
use like
var PmtFreq = Request.Form["pmtFreq"];
just Remove 'form="FormCalcInput"' from select then it will ok.

#Html.RenderAction with Ajax Form ASP.NET Mvc3 c#

I have a scenario where i need some code setup when a control renders. I have a widget that'll be used on a number of pages called a QuickRate:
I'm trying to call it like so in my cshtml file:
<div class="dragbox" id="quick-rate">
<h2>Retrieve a Quick Rate</h2>
#Html.Action("Create", "QuickRate")
</div>
and then in the create on the QuickRateController.cs I have:
public ActionResult Create()
{
var model = new QuickRateModel();
model.Products = currentUser.GetProducts(dataRepository).ToSelectList(p => p.ProductId, p => p.ProductName);
return View("QuickRateResult", model);
}
i then have a QuickRatePartial.cshtml file that contains the following:
#model Project.Web.Models.QuickRateModel
#{
Layout = "";
AjaxOptions options = new AjaxOptions()
{
HttpMethod = "Post",
UpdateTargetId = "quick-rate-content"
};
}
<div class="clearfix">
#using (Ajax.BeginForm("GetQuickRate", "QuickRate", null, options, new { #id="quick-rate-form" }))
{
<fieldset>
#Html.DropDownListFor(model => model.ProductId, Model.Products)
#Html.ValidationMessageFor(model => model.ProductId)
<select data-val="true" name="DropDown1" data-bind="
options: Items1,
optionsText :'ItemName',
value: SelectedName
">
</select>
<select data-val="true" name="DropDown2" id="DropDown2" data-val-required="Please select an Item." data-bind="
options: SelectedItem().MoreItems,
optionsText: 'Text',
optionsValue: 'Text',
value: MoreItem,
optionsCaption: 'Select One'
"></select>
<div class="clearfix">
#Html.ValidationMessageFor(model => model.MoreItems)
</div>
<div>
<input type="submit" value="Get Quick Rate" />
</div>
<div id="quick-rate-content"></div>
</fieldset>
}
</div>
try as i might I can't get the form to render at all.. just wondering if you had any suggestions?
Cheers!
You've named the file quickratepartial.cshtml but in the action you are looking for a view called quickrateresult. Is this correct?

Categories