The short and "straight" question:
A Controller action method (A) is called by a form with some parameters. In the same View, there is another form, which when submitted calls another action method (B) in the same controller.
How can I access the values of (B) form (but essentially they are the content values of dropdowns and textboxes) from the action method A?
The Long and winding explanation:
I have a View with two forms, like this:
using (Html.BeginForm("List", "Rapporti"))
{
<span>Ricerca Rapporti per Linea </span>
#Html.DropDownList("KLinea",
new SelectList(new RapportiCT.Domain.Entities.RapportiEntities().TLinea, "KLinea", "DLinea")
, "Scegli una linea");
<span>Data inizio</span>
#Html.TextBox("startDate", DateTime.Now.AddDays(-4).ToShortDateString(), new { #class = "dateTextBox" });
<span>Data fine</span>
#Html.TextBox("endDate", DateTime.Now.AddDays(-1).ToString("dd/MM/yyyy"), new { #class = "dateTextBox" })
<input type="submit" value="Cerca" />
}
if (Model.Count() > 0)
{
var lastArticolo = "";
<h2>Rapporti Capoturno #Model.First().rapportoCT.DLinea</h2>
<table>
#foreach (var rapporto in Model)
{
if (lastArticolo != rapporto.rapportoCT.DCodArt)
{
<tr>
<td class="td_title">
#rapporto.rapportoCT.DCodArt
</td>
<td colspan="3" class="td_title">
#rapporto.rapportoCT.DDescArt
</td>
<td class="td_title">
Rendimento
</td>
<td class="td_title">
#Pallet control.
</td>
<td class="td_title">
#Pallet accanton.
</td>
<td class="td_title">
Ore fermo linea
</td>
</tr>
lastArticolo = rapporto.rapportoCT.DCodArt;
}
using (Html.BeginForm("ControlloQualita", "Rapporti"))
{
<tr>
<td class="td_detail">
#rapporto.rapportoCT.Data
</td>
<td class="td_detail">
#rapporto.rapportoCT.Turno
</td>
<td class="td_detail">
#rapporto.rapportoCT.Lettera
</td>
<td class="td_detail">
#rapporto.rapportoCT.DNota
</td>
<td class="td_detail">
#rapporto.RendimentoLinea
</td>
<td class="td_detail">
#Html.TextBox("PalletControllati", rapporto.PalletControllati, new { style="width:50px" })
</td>
<td class="td_detail">
#Html.TextBox("PalletAccantonati", rapporto.PalletAccantonati, new { style = "width:50px" })
</td>
<td class="td_detail">
#Html.TextBox("OreFermoLinea", rapporto.OreFermoLinea, new { style = "width:50px" })
</td>
<td>
<input type="submit" value="Salva" />
</td>
</tr>
}
}
</table>
}
else
{
#:Nessun record trovato
}
Both forms post to the same RapportiController: the first form is used to query the database and show the resulting records, with the second one I'd like to update the database record.
View (snapshot):
So, my Controller class is like this:
// No problem here
public ViewResult List(int? KLinea = null, DateTime? startDate = null, DateTime? endDate = null)
{
IQueryable<VRapportiCT> qVRapporti = repository
.ViewRapporti(KLinea.Value, startDate.Value, endDate.Value);
List<VRapportiCT> lRapporti = qVRapporti.ToList();
List<RapportoRendimentoViewModel> listRRVM = new List<RapportoRendimentoViewModel>();
foreach (var rapporto in lRapporti)
{
RapportoRendimentoViewModel rrVM = new RapportoRendimentoViewModel();
rrVM.rapportoCT = rapporto;
rrVM.RendimentoLinea = repository.GetRendimentoLinea(rapporto);
rrVM.PalletControllati = "0";
rrVM.PalletAccantonati = "0";
rrVM.OreFermoLinea = "0";
listRRVM.Add(rrVM);
}
return View(listRRVM);
}
public RedirectToRouteResult ControlloQualita(int PalletControllati, int PalletAccantonati, int OreFermoLinea)
{
// How can I access the 1°form values here (a.k.a. the DropDown and Date text box values?
// ...Fake values, only to assert that the parameters get passed to the action...
RouteValueDictionary dic = new RouteValueDictionary();
dic.Add("KLinea", 55);
dic.Add("startDate", DateTime.Now.AddDays(-4));
dic.Add("endDate", DateTime.Now);
return RedirectToAction("List", "Rapporti", dic);
}
I see 2 options here:
Store last submitted "List" form in, lets say, Session, or TempData, or any other storage you like and restore these values on "ControlloQualita" form submission. This approch assumes that you need last submitted values from "List" form rather than latest.
Intercept "ControlloQualita" form submission in order to append values of "List" form to the request. This can be achieved with javascript by adding hidden inputs to the "ControlloQualita" form.
Related
I have searched for help but can find any topic that could help me.
I have a table like this
<table id="tableftest" class="table table-striped table-vmiddle">
<thead>
<tr>
<th data-column-id="" data-sortable="false">
<input type="checkbox" id="checkall" title="chọn tất cả" onclick="" />
</th>
<th data-column-id="ip">IP</th>
<th data-column-id="network" hidden="hidden">Network</th>
<th data-column-id="sender">GateWay</th>
<th data-column-id="received">SubnetMask</th>
<th data-column-id="viewdetail">VPS được gán</th>
#*<th data-column-id="commands" data-formatter="commands" data-sortable="false"></th>*#
</tr>
</thead>
<tbody>
#foreach (VPSIP ipitem in ip)
{
<tr>
#if (ipitem.VPSID != null)
{
<td></td>
}
else
{
<td>
<input type="checkbox" class="ipDelListClass" name="ipDelList" value="#ipitem.IpID" />
</td>
}
<td>#(ipitem.IPAddress)</td>
<td hidden="hidden">#ipitem.NetworkRanx.NetworkAddress</td>
<td>#(ipitem.NetworkRanx.Gateway)</td>
<td>#ipitem.NetworkRanx.SubnetMask</td>
#if (ipitem.VPSID != null)
{
<td>#(ipitem.VPSs.VPSName)</td>
#*<td></td>*#
}
else
{
<td></td>
#*<td>
<button title="Xóa ip" class="btn btn-danger zmdi zmdi-delete" data-toggle="modal" data-target="#IpDel_#ipitem.IpID" style="font-size:medium"></button>
</td>*#
}
</tr>
}
</tbody>
</table>
When I check all checkboxs in table and click button delete, it will post data to this controller
[HttpPost]
public ActionResult IPDeleteMany(FormCollection f)
{
var ipDelArray = f.Get("ipDelList");
ServerBusiness serBu = new ServerBusiness();
string[] ipDelList = ipDelArray.Split(',');
try
{
foreach (string ipId in ipDelList)
{
var iprow = serBu.getIPById(int.Parse(ipId));
serBu.removeIPById(iprow);
}
TempData["Success"] = "IP đã bị xóa!";
return RedirectToAction("ViewListIP", "TechnicalStaff");
}
catch
{
TempData["Error"] = "Lỗi!";
return RedirectToAction("ViewListIP", "TechnicalStaff");
}
}
When it runs, it only get values of rows that is visible, not all the rows in table.
Is there anyway to get all of values checked in table include invisible rows?
change your hidden="hidden" to style="display:none;".
And for you other pages, because you didnt use Ajax your data isn't exist in fact, so you can:
use Ajax and hide your old rows and append new rows where exist
all of your desired rows in your html however some of them be
hidden.
force your users to submit current page data and then switch pages.
I have a issue with a view being populated from a WCF service into a partial view. Everything works just fine and the model contains the data necessary, but somehow it keeps getting this error. I can clearly see the value for the ProduktDto so it isn't null at all, but still says it is.
Have heard that the error could be in the connectionString so I include it here:
<add name="SpelDatabasContainer" connectionString="metadata=res://*/SpelDatabas.csdl|res://*/SpelDatabas.ssdl|res://*/SpelDatabas.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=SpelAffarenDatabas;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Havent found the answer for this after serious googling.
Here is the code for the view:
#model List<SpelAffarWCF.ProduktDto>
<table class="table table-responsive">
<tr>
<th>Id</th>
<th>Namn</th>
<th>Beskrivning</th>
<th>Utgivningsår</th>
<th>MP</th>
<th>SP</th>
<th>Pris</th>
<th>Utgivare</th>
<th>Konsoler</th>
<th>Genres</th>
<th>Aktiv order antal</th>
</tr>
#foreach (var spel in Model)
{
<tr>
<td title="Spelets Id">#spel.Id</td>
<td title="Spelets jävla namn">#spel.Namn</td>
<td title="#spel.Beskrivning">För musen över mig..</td>
<td title="När det släpptes">#spel.Utgivningsår</td>
<td title="Multipläjer">#Html.CheckBox("checkboxMP", spel.Multiplayer)</td>
<td title="Singlpläjer">#Html.CheckBox("checkboxSP", spel.Singleplayer)</td>
<td title="Spelet kostar faktiskt såhär mycket">#spel.Pris</td>
<td title="Id: #spel.Utgivare.Id, Spel: #spel.Utgivare.Produkter.Count()">#Html.ActionLink(spel.Utgivare.Namn, "EditPublisher", new { id = spel.Utgivare.Id })</td>
#if (spel.Konsoler.Count() > 0)
{
<td>
#foreach (var konsol in spel.Konsoler)
{
<p class="cellEntity">#konsol.Namn</p>
}
</td>
}
else
{
<td>Ingen.</td>
}
#if (spel.Genres.Count() > 0)
{
<td>
#foreach (var genres in spel.Genres)
{
<p class="cellEntity">#genres.Namn</p>
}
</td>
}
else
{
<td>Ingen genre.</td>
}
#if (spel.SpelPerOrders.Count() > 0)
{
<td>
#foreach (var spelOrder in spel.SpelPerOrders)
{
<p class="cellEntity">Id: #spelOrder.OrderId, #spelOrder.Antal st</p>
}
</td>
}
else
{
<td>Finns inte i någon order.</td>
}
<td>
<input type="button" value="Lägg till i kundvagn" onclick="AddToCart(#spel.Id)" />
</td>
</tr>
}
</table>
The error indicates it's either the spel.Utgivare.Produkter.Count() or spel.Konsoler.Count() call; the parameter of the Linq Count extension method is named source.
Ive made some checkboxes in a View. The checkboxes is implemented via the ViewModel with bool properties. I'm currently trying to change a query in the controller to "date" or "month" depending if the checkbox has been checked. However in the Controller it always jumps the the "else statement" even if "Month" has been checked. Month is always False.
I suspect the JavaScript code might be wrong.
This User Interface:
In my Controller method i try to do the following:
Controller:
var request = GoogleAnalyticsService.Data.Ga.Get("ga:59380223", start, end, "ga:visitors");
var request = GoogleAnalyticsService.Data.Ga.Get("ga:59380223", start, end, "ga:visitors");
if (model.Month)
{
request.Dimensions = "ga:month";
request.Sort = "-ga:month";
}
else
{
request.Dimensions = "ga:date";
request.Sort = "-ga:date";
}
request.MaxResults = 10000;
Google.Apis.Analytics.v3.Data.GaData d = request.Execute();
In The view ive implemented my Viewmodel and tried writing some javascript checking if what checkbox have ´been checked and if to return true or false:
View:
<table class="adminContent">
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.StartDate):
</td>
<td class="adminData">
#Html.EditorFor(model => model.StartDate)
</td>
</tr>
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.EndDate):
</td>
<td class="adminData">
#Html.EditorFor(model => model.EndDate)
</td>
</tr>
<tr>
<td class="data" colspan="2">
#Html.CheckBoxFor(model => model.Date, new { id = "Day" }) // -- Checkbox Date
#Html.LabelFor(model => model.Date)
</td>
</tr>
<tr>
<tr>
<td class="data" colspan="2">
#Html.CheckBox("chkMonth", new { #onclick = "updatemyhidden(this)" }) // -- Checkbox Month
#Html.HiddenFor(model => model.Month, new { id = "Month" })
#Html.LabelFor(model => model.Month)
</td>
</tr>
</tr>
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.GAStatisticsId ):
</td>
<td class="adminData">
#Html.DropDownList("GAStatisticsId", Model.AvailableGAStatistics)
<input type="button" id="GAStatisticsReport-Submit" class="t-button" value="#T("Admin.Common.Search")" />
</tr>
</table>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="/Scripts/jquery.min.js"></script>
<script type="text/javascript">
$("#GAStatisticsReport-Submit").click(function () {
if ($("select[name='GAStatisticsId'] option:selected").text() == "Visitors Report")
drawChartVisitors()
if ($("select[name='GAStatisticsId'] option:selected").text() == "Orders Report")
drawChartOrders()
if ($("select[name='GAStatisticsId'] option:selected").text() == "Conversion Report")
drawConversion()
function updatemyhidden(chkbox) {
$("#Month").val(chkbox.checked);
}
})
google.load("visualization", "1", { packages: ["corechart"] });
google.load("visualization", "1", { packages: ["treemap"] });
function drawChartVisitors() {
$.get('/GAStatistics/GetVisitors', {
StartDate: $('##Html.FieldIdFor(model => model.StartDate)').val(),
EndDate: $('##Html.FieldIdFor(model => model.EndDate)').val(),
},
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('date', 'Date');
tdata.addColumn('number', 'Visitors');
for (var i = 0; i < data.length; i++) {
if ($("#Month").is(":checked")) {
var dateStr = data[i].Date.substr(0, 4);
}
else {
var dateStr = data[i].Date.substr(0, 4) + "-" + data[i].Date.substr(4, 2) + "-" + data[i].Date.substr(6, 2);
}
tdata.addRow([new Date(dateStr), parseInt(data[i].Visitors)]);
}
The if-statements in the controller dosnt seem to operate depending on what i select in the view.
Note: im not using httpPost/get as the data is loaded with Google Charts and i don't want the whole page to re-aload each time a new request is selected.
Is because you set bool field on the month so it will rendered as true/false for your checkbox. You have a look at the rendered HTML for the month checkbox., and no matter you checked or not the data still send back to server as true/false depend what been set when rendering the page. This value will never change.
So i suggest you either add one more property in your viewmodel to keep try check/unchecked state and in the view rendered it as hidden field and update this hidden field whenever checkbox is ticked/unticked.
Or the month field render as hidden field and add one more checkbox in the page to update the month field when checkbox is checked/unchecked
Let say we use 2nd approach, the code will look something like this, (I did not test the code below). I hope this helps:
#Html.CheckBox("chkMonth", new { #onclick = "updatemyhidden(this)" })
#Html.HiddenFor(model => model.Month)
<script type="text/javascript">
function updatemyhidden(chkbox) {
$("#Month").val(chkbox.checked);
}
</script>
I'm creating radio button dynamically.
#model IList<HireItemModel.HireItemSeparatetModel>
#foreach (var item in Model)
{
var val = item.pId;
<tr>
<td>
<input type="checkbox" name="chk_group" value="#val" />
</td>
<td>
#Html.DisplayFor(modelItem => item.pname)
</td>
<td> - $</td>
<td>
#Html.DisplayFor(modelItem => item.price)
</td>
</tr>
}
So I want to check the one of the check box is click in java script.
So How can I do it?
I'm using C# asp.net MVC.
Each checkbox has a checked property:
var i, tmpVal,
checkboxes = document.getElementsByName("chk_group"); // array of checkboxes
for(i = 0; i < checkboxes.length; i++){
//based on your code, it looks like you may want to check the value prop
tmpVal = checkboxes[i].getAttribute("value");
if (checkboxes[i].checked) {
// ...do something
}
}
I have a View that contains automatically generated input boxes of type text. When I click the "Email Results" button, the code takes you over to the EmailResults Action within the CalculatedResults controller. So far, so good. But, even though I have FormCollection as a parameter in the EmailResults Action, it's coming through as null, and I don't know why. I need to be able to capture the text boxes from the form- please help!!. In my View code below, the generated text boxes are a little past halfway down.
My View Code
#using (Html.BeginForm("EmailResults", "CalculatedResults", FormMethod.Post, new { data_ajax = "false" }))
{
<table>
<thead>
<tr>
<td>Ingredient</td>
<td>Qty (gm)</td>
</tr>
</thead>
#foreach (var i in Model)
{
if (Convert.ToDecimal(i.Qty) < 0)
{
<tr>
<td style="border: 1px solid red; color: red;">#i.Ingredient</td>
<td style="border: 1px solid red; color: red;">#i.Qty</td>
</tr>
}
else if (Convert.ToDecimal(i.Qty) == 0m)
{
continue;
}
else
{
if (i.Ingredient.Contains("Active"))
{
<tr>
<td>#i.Ingredient<br />
<input type="text" name="actives" /></td>
<td>#i.Qty</td>
</tr>
}
else
{
<tr>
<td>#i.Ingredient</td>
<td>#i.Qty</td>
</tr>
}
}
}
</table>
}
<div style="float: left">
#Html.ActionLink("Email Results", "EmailResults", "CalculatedResults", new { crpk = #ViewBag.crpk }, new { data_icon = "arrow-r", data_role = "button" })
</div>
My Controller Code
public ViewResult EmailResults(int crpk, FormCollection collection)
{
CapWorxQuikCapContext context = new CapWorxQuikCapContext();
//List<string> variables = new List<string>();
//foreach (var item in Request.Form)
//{
// variables.Add(item.ToString());
//}
CalculatedResults cr = (from i in context.CalculatedResults where i.Pk == crpk select i).SingleOrDefault();
Helpers.Email.EmailResults(cr);
return View();
}
Here's a screenshot:
The formCollection will only come across when you submit the form to the controller. Either
Use <input type="submit" value="Email Results" />
Wire up a jquery handler to the ActionLink that you have created that submits the form for you.