I have a database which i would like to fill with a filler-method. I wish to call on this method from the Index-view in my MVC-project. I have tested that the method works by running it each time the index.cshtml is run, and it fills the table. The only problem with this is that if I refresh the index-page, the table gets filled with the exact same data once again. Which results in me getting two of every item.
So I have come to the conclusion that I want to bind my filler()-method to a button on the index-page to fill the table. My question is then:
How do I directly bind a method to a button in my project?
Extra info:
The filler-method is in its own class called DBFiller.cs, and when I set it to run on index launch I added DBfiller.filler() in the actionresult of my controller.
Code:
DBFiller.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Oblig1.BLL;
using Oblig1.Model;
using Oblig1.DAL;
namespace Oblig1
{
public class DBFiller
{
public void Filler()
{
var userDb = new UserBLL();
var itemDb = new ItemBLL();
var city1 = new Cities();
var city2 = new Cities();
var city3 = new Cities();
city1.Cityname = "Oslo";
city1.Postcode = "9382";
city2.Cityname = "Trondheim";
city2.Postcode = "2301";
city3.Cityname = "Bergen";
city3.Postcode = "1723";
var user1 = new Users()
{
Address = "Moroveien 7",
Firstname = "Martin",
Surname = "Hermansen",
Email = "mh#mh.no",
Password = "mhmhmh",
Phonenr = "93929392",
Postcode = "9382",
cities = city1
};
var user2 = new Users()
{
Address = "Bakvendtgata 8",
Firstname = "Hanne",
Surname = "Lande",
Email = "hl#hl.no",
Password = "hlhlhl",
Phonenr = "82711212",
Postcode = "2301",
cities = city2
};
var user3 = new Users()
{
Address = "Fisefin Aveny 14",
Firstname = "Voldemort",
Surname = "Olsen",
Email = "vo#vo.no",
Password = "vovovo",
Phonenr = "12672891",
Postcode = "1723",
cities = city3
};
var item1 = new Items()
{
Currentstock = 40,
Itemname = "Blanding",
Itemprice = 99,
Itemtype = "Pasta",
PictureURL = "/img/pasta_blanding.png",
Itemid = 78
};
var item2 = new Items()
{
Currentstock = 17,
Itemname = "Fusilli",
Itemprice = 119,
Itemtype = "Pasta",
PictureURL = "/img/pasta_fusilli.png",
Itemid = 63
};
var item3 = new Items()
{
Currentstock = 80,
Itemname = "Farfalle",
Itemprice = 69,
Itemtype = "Pasta",
PictureURL = "/img/pasta_farfalle.png",
Itemid = 30
};
var item4 = new Items()
{
Currentstock = 63,
Itemname = "Colored Fusilli #1",
Itemprice = 45,
Itemtype = "Pasta",
PictureURL = "/img/pasta_fusilli_farget.png",
Itemid = 22
};
var item5 = new Items()
{
Currentstock = 3,
Itemname = "Colored Fusilli #2",
Itemprice = 33,
Itemtype = "Pasta",
PictureURL = "/img/pasta_fusilli_farget2.png",
Itemid = 98
};
var item6 = new Items()
{
Currentstock = 77,
Itemname = "Macaroni",
Itemprice = 25,
Itemtype = "Pasta",
PictureURL = "/img/pasta_macaroni.png",
Itemid = 76
};
var item7 = new Items()
{
Currentstock = 80,
Itemname = "Measure",
Itemprice = 299,
Itemtype = "Tools",
PictureURL = "/img/pasta_messure.png",
Itemid = 59
};
var item8 = new Items()
{
Currentstock = 14,
Itemname = "Multitool",
Itemprice = 499,
Itemtype = "Tool",
PictureURL = "/img/pasta_multitool.png",
Itemid = 69
};
var item9 = new Items()
{
Currentstock = 88,
Itemname = "Penne",
Itemprice = 19,
Itemtype = "Pasta",
PictureURL = "/img/pasta_penne.png",
Itemid = 79
};
var item10 = new Items()
{
Currentstock = 45,
Itemname = "Roller",
Itemprice = 59,
Itemtype = "Tool",
PictureURL = "/img/pasta_ruller.png",
Itemid = 79
};
var item11 = new Items()
{
Currentstock = 179,
Itemname = "Spoon",
Itemprice = 39,
Itemtype = "Tool",
PictureURL = "/img/pasta_sleiv.png",
Itemid = 110
};
var item12 = new Items()
{
Currentstock = 17,
Itemname = "Spagetti",
Itemprice = 9,
Itemtype = "Pasta",
PictureURL = "/img/pasta_penne.png",
Itemid = 79
};
itemDb.registerItem(item1);
itemDb.registerItem(item2);
itemDb.registerItem(item3);
itemDb.registerItem(item4);
itemDb.registerItem(item5);
itemDb.registerItem(item6);
itemDb.registerItem(item7);
itemDb.registerItem(item8);
itemDb.registerItem(item9);
itemDb.registerItem(item10);
itemDb.registerItem(item11);
itemDb.registerItem(item12);
userDb.setIn(user1);
userDb.setIn(user2);
userDb.setIn(user3);
}
}
}
My attempt at adding it in the index-launcher in my User-Controller:
namespace Oblig1.Controllers
{
public class UserController : Controller
{
public ActionResult Index()
{
var model = new UserBLL();
var filler = new DBFiller();
filler.Filler();
List<Item> allItems = model.getItems();
return PartialView(allItems);
}
}
}
Index.cshtml if it helps any:
#using Oblig1
#model IEnumerable<Oblig1.Model.Item>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<br />
<br />
<head>
<title>Index</title>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</head>
#if (Model != null)
{
<div class="row">
#foreach(var item in Model)
{
<div class="col-sm-6 col-md-3">
<div class="thumbnail">
<img src="#item.pictureURL" alt="...">
<div class="caption">
<h3>#item.itemname</h3>
<p>Antall på lager: #item.currentstock<br />kr #item.itemprice,00</p>
<button class="btn btn-success">#Html.ActionLink("Add to Cart", "AddToCart", new { id = item.itemid }, null)</button>
</div>
</div>
</div>
}
</div>
}
Attempt at filler-call by JS:
#model IEnumerable<Oblig1.Model.Item>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<br />
<br />
<head>
<title>Index</title>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/jscript">
$('#fill').click(function () {
var url = "/UserController/Filler";
$.post( url);
});
</script>
</head>
<button class="btn btn-success" id="fill" value="Fill Database"> </button>
Controller:
public ActionResult Filler()
{
var filler = new DBFiller();
filler.Filler();
return View("Index");
}
You can move the logic of filling to another action method and call it using jquery Ajax call on the click of the button
EDIT:
Please refer the below link for sample
http://www.itorian.com/2013/02/jquery-ajax-get-and-post-calls-to.html
Basically below is the code to link the click of your button with Action method
<script type="text/javascript">
$(document).ready(function()
{
$('#ButtonID').click(function () {
var url = "/ControllerName/YourActionMethod";
$.post( url);
});
});
Add the above code in your page with appropriate url and button id
Related
I am making a tweak to an app and doing an UPDATE. It throws me the following error:
There is no ViewData item of type 'IEnumerable' that has the key 'Conve'.
My DropDownList loads the data perfectly but when I select any of that list to use its value and change it to the value that is in my BD it throws that error
Model: TableAsign.cs
public class TableAsign
{
public long IdCliente { get; set; }
public string nombre { get; set; }
}
Controller: MastController.cs
[Authorize]
public ActionResult Asign_Conv(int idUsuario)
{
List<Models.TableAsign> lst = null;
using (TPConveniosEntities db = new TPConveniosEntities())
{
lst = (from d in db.Cliente
orderby d.nombre
select new TableAsign
{
IdCliente = d.idCliente,
nombre = d.nombre
}).ToList();
}
List<SelectListItem> items = lst.ConvertAll(d =>
{ return new SelectListItem()
{ Text = d.nombre.ToString(),
Value = d.IdCliente.ToString(),
Selected = false
};
});
ViewBag.items = items;
using (TPConveniosEntities db = new TPConveniosEntities())
{
Usuario user = db.Usuario.FirstOrDefault(u => u.idUsuario == idUsuario);
return View(user);
}
}
In this part it performs the UPDATE and it seems to me that it has to do when I bring the value of my DropDownList with my long variable, it throws me the error and then when I consult my DB I see that if it performs the UPDATE but giving me that error
[Authorize]
[HttpPost]
public ActionResult Asign_Conv(FormCollection collection)
{
using (TPConveniosEntities contexto = new TPConveniosEntities())
{
var idUsuario = Convert.ToInt32(collection["IdUsuario"].Trim());
Usuario user = contexto.Usuario.FirstOrDefault(u => u.idUsuario == idUsuario);
var userName = collection["usuario"].Trim();
long IdCliente = Convert.ToInt32(collection["Convenio"].Trim());
user.userName = userName;
user.idCliente = IdCliente;
contexto.SaveChanges();
return View(user);
}
}
VIEW: Asign_Conv.cshtml
#using TPConvenios.App_Data;
#model Usuario
#{
Layout = null;
AjaxOptions ajaxOpciones = new AjaxOptions
{
UpdateTargetId = "cuerpoPopUpGenerico2",
InsertionMode = InsertionMode.Replace,
OnSuccess = "OnSuccess_Asign",
OnFailure = "OnFailure"
};
List<SelectListItem> items = (List<SelectListItem>)ViewBag.items;
}
<div id="contenedor" style="margin: 15px 30px">
#using (Ajax.BeginForm("Asign_Conv", "Mast", null, ajaxOpciones, new { id = "Asign_Conv" }))
{ #Html.ValidationSummary(true);
<input type="hidden" name="idUsuario" id="idUsuario" value="#(null != Model ? Model.idUsuario : 0)" />
<p>
<input name="usuario" type="text" id="usuario" class="usuario" placeholder="Usuario" value="#(null != Model ? Model.userName : String.Empty)"/>
</p>
<p>
#Html.DropDownList("Convenio", items, "Seleccione el Convenio", new { #class = "form-control" })
</p>
<p id="bot">
<input name="submit" type="submit" id="submit" value="Asignar" class="botonNuevo" style="float: right" />
</p>
}
</div>
I managed to solve my problem by bringing me the code with which I load my DropdownList, and pasting it to the POST where it performs UPDATE.
staying this way
[Authorize]
[HttpPost]
public ActionResult Asign_Conv(FormCollection collection)
{
using (TPConveniosEntities contexto = new TPConveniosEntities())
{
var idUsuario = Convert.ToInt32(collection["IdUsuario"].Trim());
Usuario user = contexto.Usuario.FirstOrDefault(u => u.idUsuario == idUsuario);
var userName = collection["usuario"].Trim();
long IDCliente = Convert.ToInt32(collection["Conve"].Trim());
/*********** ESTO FUE LO QUE COPIE PARA QUE FUNCIONARA **********/
List<Models.TableAsign> lst = null;
using (TPConveniosEntities db = new TPConveniosEntities())
{
lst = (from d in db.Cliente
orderby d.nombre
select new TableAsign
{
IdCliente = d.idCliente,
nombre = d.nombre
}).ToList();
}
List<SelectListItem> items = lst.ConvertAll(d =>
{
return new SelectListItem()
{
Text = d.nombre.ToString(),
Value = d.IdCliente.ToString(),
Selected = false
};
});
ViewBag.items = items;
/*************************** HASTA AQUI **********************/
user.userName = userName;
user.idCliente = IDCliente;
contexto.SaveChanges();
return View(user);
}
}
Please help me. My dropdownlist showing System.Web.SelectListItem in debug mode but not showing actual text that I defined in the list. Can anyone please help. How make the controller to have the text that I define in the list. Also my dropdownlist is not blinding in selecting. Please help me
This is how it look like, please take a look
Here the my model:
public List<SelectListItem> KeywordOptions { get; set; }
public int KeywordOptionsSelected { get; set; }
public List<SelectListItem> MarketandRevenueOptions { get; set; }
public int MarketandRevenueOptionsSelected { get; set; }
public List<SelectListItem> KeywordsList { get; set; }
public int KeywordsListSelected { get; set; }
Here is the controller:
public ActionResult WACCtest(string RegionID1, bool HongKong = false, bool China = false, bool marketmultiples = false, bool dcf = false)
{
var objWACC = new WACC();
XmlDocument xmlTmp = webS.GetWaccOptionsIndustries();
objWACC.Industries = new List<Industry>();
XmlDocument nodeCompsTmp = webS._Test_CompsFilter();
objWACC.Companies = new List<ComparableCompanies>();
XmlDocument nodeMktRevenueTmp = webS._Test_MktCapRevenue();
objWACC.MrkCapRevenue = new List<MrkCapAndRevenue>();
XmlNodeList nodeListMktCap1 = nodeMktRevenueTmp.GetElementsByTagName("Mkt_Cap");
XmlNodeList nodeListRevenue = nodeMktRevenueTmp.GetElementsByTagName("Revenue");
for (int i = 0; i < nodeListMktCap1.Count; i++)
{
MrkCapAndRevenue objMktCapRevenue = new MrkCapAndRevenue();
objMktCapRevenue.Mrk_Cap = double.Parse(nodeListMktCap1[i].InnerText.Trim());
objMktCapRevenue.Revenue = nodeListRevenue[i].InnerText.Trim();
objWACC.MrkCapRevenue.Add(objMktCapRevenue);
}
XmlNodeList nodeListCompID = nodeCompsTmp.GetElementsByTagName("Company_ID");
XmlNodeList nodeListCompName = nodeCompsTmp.GetElementsByTagName("Company_Name");
XmlNodeList nodeListStockTicker = nodeCompsTmp.GetElementsByTagName("Stock_Ticker");
XmlNodeList nodeListIPO = nodeCompsTmp.GetElementsByTagName("IPO_Date");
XmlNodeList nodeListCompWeb = nodeCompsTmp.GetElementsByTagName("Company_Website");
XmlNodeList nodeListCompDescr = nodeCompsTmp.GetElementsByTagName("Company_Description");
for (int i = 0; i < nodeListCompID.Count; i++)
{
ComparableCompanies objComparableComps = new ComparableCompanies();
objComparableComps.Company_ID = int.Parse(nodeListCompID[i].InnerText.Trim());
objComparableComps.Company_Name = nodeListCompName[i].InnerText.Trim();
objComparableComps.Stock_Ticker = nodeListStockTicker[i].InnerText.Trim();
objComparableComps.IPO_Date = DateTime.Parse(nodeListIPO[i].InnerText.Trim());
objComparableComps.Company_Website = nodeListCompWeb[i].InnerText.Trim();
objComparableComps.Company_Description = nodeListCompDescr[i].InnerText.Trim();
objWACC.Companies.Add(objComparableComps);
}
//EC: add the columns one by one
XmlNodeList nodeListGICCode = xmlTmp.GetElementsByTagName("GIC_Code");
XmlNodeList nodeListIndName = xmlTmp.GetElementsByTagName("Industry_Name");
XmlNodeList nodeListIndLvl = xmlTmp.GetElementsByTagName("Industry_Level");
XmlNodeList nodeListParentGICCode = xmlTmp.GetElementsByTagName("Parent_GIC_Code");
for (int i = 0; i < nodeListGICCode.Count; i++)
{
Industry indTemp = new Industry();
indTemp.GIC_Code = int.Parse(nodeListGICCode[i].InnerText.Trim());
indTemp.Industry_Name = nodeListIndName[i].InnerText.Trim();
indTemp.Industry_Level = int.Parse(nodeListIndLvl[i].InnerText.Trim());
indTemp.Parent_GIC_Code = 0;
if (indTemp.Industry_Level != 1)
{
indTemp.Parent_GIC_Code = int.Parse(nodeListParentGICCode[i].InnerText.Trim());
} //EC: no need to check the parent if industry level = 1 since it has no parent (will result an exception for level 1)
objWACC.Industries.Add(indTemp);
}
string strValDate = Request.QueryString["ValuationDate"] ?? "2020-01-01";
string strIndustrySelected = Request.QueryString["IndustrySelected"] ?? "0"; // BW: the selected varaables are based on index value
string strLocationSelected = Request.QueryString["LocationSelected"] ?? "1";
string strFV = Request.QueryString["FairValue"] ?? "0.0";
string strRFR = Request.QueryString["RiskFreeRate"] ?? "0.0";
string strBETA = Request.QueryString["Beta"] ?? "0.0";
string strMRPs = Request.QueryString["Mrp"] ?? "0.0";
string strCAPM = Request.QueryString["CAPM"] ?? "0.0";
string strTAXRATE = Request.QueryString["TaxRate"] ?? "0.0";
string strLendingRate = Request.QueryString["LendingRate"] ?? "0.0";
string strWE = Request.QueryString["WE"] ?? "0.0";
string strWD = Request.QueryString["WD"] ?? "0.0";
string strAFTaxCod = Request.QueryString["AFTaxCod"] ?? "0.0";
string strBetaSelected = Request.QueryString["BetaSelected"] ?? "0";
string strMrpSelected = Request.QueryString["MrpSelected"] ?? "0";
string strSizePr = Request.QueryString["SizePremium"] ?? "0.0";
string strCompSpecPr = Request.QueryString["ComSpecPr"] ?? "0.0";
string strLendRatePr = Request.QueryString["LendRatePr"] ?? "0.0";
string strOtherPr = Request.QueryString["OtherPr"] ?? "0.0";
string strIndustries = Request.QueryString["Industries"] ?? "0";
string strKeywordOptions = Request.QueryString["KeywordOptions"] ?? "0";
string strKeywordsSelected = Request.QueryString["KeywordOptionsSelected"] ?? "TEST 2";
string strMarketandRevenueOptionsSelected = Request.QueryString["MarketandRevenueOptionsSelected"] ?? "0";
string strKeywordsListSelected = Request.QueryString["KeywordsListSelected"] ?? "0";
//BW: Define variable as double integer for the selecting Values
int intIndSel = 0;
int intLocSel = 0;
double dblFV = 0.0;
double dblRFR = 0.0;
double dblBeta = 0.0;
double dblMRP = 0.0;
double dblCAPM = 0.0;
double dblTAXRATE = 0.0;
double dblLendingRate = 0.0;
double dblWE = 0.0;
double dblWD = 0.0;
double dblAFTaxCod = 0.0;
int intBetSel = 0;
int intMrpSel = 0;
string[] strVD = new string[3];
DateTime dtVD = new DateTime(2020, 01, 01);
List<string> listIndustry = new List<string>();
int intKeywordsSel = 0;
int intMarketandRevenueOptionsSel = 0;
int intKeywordsListSel = 0;
double dblSP = 0.0;
double dblCSP = 0.0;
double dblLRP = 0.0;
double dblOPR = 0.0;
try { intIndSel = int.Parse(strIndustrySelected); } catch { intIndSel = 0; } //EC: add 1 to take into account of the default item
try { intLocSel = int.Parse(strLocationSelected); } catch { intLocSel = 0; }
try { dblFV = double.Parse(strFV); } catch { dblFV = 0.0; }
try { dblRFR = double.Parse(strRFR); } catch { dblRFR = 0.0; }
try { dblBeta = double.Parse(strBETA); } catch { dblBeta = 0.0; }
try { dblMRP = double.Parse(strMRPs); } catch { dblMRP = 0.0; }
try { dblCAPM = double.Parse(strCAPM); } catch { dblCAPM = 0.0; }
try { dblTAXRATE = double.Parse(strTAXRATE); } catch { dblTAXRATE = 0.0; }
try { dblLendingRate = double.Parse(strLendingRate); } catch { dblLendingRate = 0.0; }
try { dblWE = double.Parse(strWE); } catch { dblWE = 0.0; }
try { dblWD = double.Parse(strWD); } catch { dblWD = 0.0; }
try { dblAFTaxCod = double.Parse(strAFTaxCod); } catch { dblWD = 0.0; }
try { intBetSel = int.Parse(strBetaSelected); } catch { intBetSel = 0; }
try { intMrpSel = int.Parse(strMrpSelected); } catch { intMrpSel = 0; }
try { dblSP = double.Parse(strSizePr); } catch { dblSP = 0.0; }
try { dblCSP = double.Parse(strCompSpecPr); } catch { dblCSP = 0.0; }
try { dblLRP = double.Parse(strLendRatePr); } catch { dblLRP = 0.0; }
try { dblOPR = double.Parse(strOtherPr); } catch { dblOPR = 0.0; }
try { intKeywordsSel = int.Parse(strKeywordsSelected); } catch { intKeywordsSel = 0; }
try { intMarketandRevenueOptionsSel = int.Parse(strMarketandRevenueOptionsSelected); } catch { intMarketandRevenueOptionsSel = 0; }
try { intKeywordsListSel = int.Parse(strKeywordsListSelected); } catch { intKeywordsListSel = 0; }
//BW: For testing purpose add data to list
try
{
listIndustry.Add("Consumer Discretionary");
listIndustry.Add("");
}
catch (Exception e) { Console.WriteLine(e.Message); }
try
{
strVD = strValDate.Split('-');
dtVD = new DateTime(int.Parse(strVD[0].ToString()),
int.Parse(strVD[1].ToString()),
int.Parse(strVD[2].ToString()));
}
catch
{
//dtVD = new DateTime(2018, 12, 31);
dtVD = DateTime.Now;
}
List<SelectListItem> tmpabc = new List<SelectListItem>();
tmpabc.Add(new SelectListItem() { Text = "--Select Location--", Value = "2" });
tmpabc.AddRange(webS.GetWaccOptionsOpLocations());
resetValuesInListOfSelectListItem(tmpabc);
objWACC.LocationList = tmpabc;
List<SelectListItem> tmpbeta = new List<SelectListItem>();
tmpbeta.Add(new SelectListItem() { Text = "--Select Beta--", Value = "2" });
tmpbeta.AddRange(webS.GetWaccOptionsBeta());
resetValuesInListOfSelectListItem(tmpbeta);
objWACC.BetaList = tmpbeta;
List<SelectListItem> tmpmrp = new List<SelectListItem>();
tmpmrp.Add(new SelectListItem() { Text = "--Select Mrp--", Value = "3" });
tmpmrp.AddRange(webS.GetWaccOptionsMRP());
resetValuesInListOfSelectListItem(tmpmrp);
objWACC.MrpList = tmpmrp;
//BW: return a varible that have the values that user select or input from the UI
objWACC.IndustrySelected = intIndSel;
objWACC.LocationSelected = intLocSel;
objWACC.FairValue = dblFV;
objWACC.RiskFreeRate = dblRFR;
objWACC.Beta = dblBeta;
objWACC.Mrp = dblMRP;
objWACC.CAPM = dblCAPM;
objWACC.TaxRate = dblTAXRATE;
objWACC.LendingRate = dblLendingRate;
objWACC.WE = dblWE;
objWACC.WD = dblWD;
objWACC.AFTaxCod = dblAFTaxCod;
objWACC.BetaSelected = intBetSel;
objWACC.MrpSelected = intMrpSel;
objWACC.SizePremium = dblSP;
objWACC.ComSpecPr = dblCSP;
objWACC.LendRatePr = dblLRP;
objWACC.OtherPr = (objWACC.SizePremium + objWACC.ComSpecPr);
objWACC.KeywordOptionsSelected = intKeywordsSel;
objWACC.MarketandRevenueOptionsSelected = intMarketandRevenueOptionsSel;
objWACC.KeywordsListSelected = intKeywordsListSel;
string strOpLocation = objWACC.LocationList[intLocSel].Text;
//string strIndustry = objWACC.IndustryList[intIndSel].Text;
string strIndustry = "";
string strBeta = objWACC.BetaList[intBetSel].Text;
string strMRP = objWACC.MrpList[intMrpSel].Text;
string strIndustrylevel = objWACC.Industries.ToString();
if (strBeta == "Beta WIND" || strBeta == "Beta BDO")
{
//BW: need to add string Industry level to webservice.
XmlDocument xmlWACCSummary = webS.GetWaccSummary(strOpLocation, strIndustry, strValDate, strMRP, strBeta, dblSP / 100, dblCSP / 100, dblLRP / 100);
//BW: Below is a temp solution to check if the returned xml is a valid WACC summary
XmlNodeList nodeWACCTmp = xmlWACCSummary.GetElementsByTagName("Relevered_Beta");
if (nodeWACCTmp[0] == null)
{
return View(objWACC);
}
nodeWACCTmp = xmlWACCSummary.GetElementsByTagName("Relevered_Beta");
objWACC.Beta = Convert.ToDouble(nodeWACCTmp[0].LastChild.InnerText);
nodeWACCTmp = xmlWACCSummary.GetElementsByTagName("WE");
objWACC.WE = Convert.ToDouble(nodeWACCTmp[0].LastChild.InnerText);
nodeWACCTmp = xmlWACCSummary.GetElementsByTagName("WD");
objWACC.WD = Convert.ToDouble(nodeWACCTmp[0].LastChild.InnerText);
nodeWACCTmp = xmlWACCSummary.GetElementsByTagName("MRP");
objWACC.Mrp = Convert.ToDouble(nodeWACCTmp[0].LastChild.InnerText);
nodeWACCTmp = xmlWACCSummary.GetElementsByTagName("CAPM");
objWACC.CAPM = Convert.ToDouble(nodeWACCTmp[0].LastChild.InnerText);
nodeWACCTmp = xmlWACCSummary.GetElementsByTagName("RFR");
objWACC.RiskFreeRate = Convert.ToDouble(nodeWACCTmp[0].LastChild.InnerText);
nodeWACCTmp = xmlWACCSummary.GetElementsByTagName("Tax_Rate");
objWACC.TaxRate = Convert.ToDouble(nodeWACCTmp[0].LastChild.InnerText);
nodeWACCTmp = xmlWACCSummary.GetElementsByTagName("Lending_Rate");
objWACC.LendingRate = Convert.ToDouble(nodeWACCTmp[0].LastChild.InnerText);
nodeWACCTmp = xmlWACCSummary.GetElementsByTagName("COD");
objWACC.AFTaxCod = Convert.ToDouble(nodeWACCTmp[0].LastChild.InnerText);
nodeWACCTmp = xmlWACCSummary.GetElementsByTagName("Other_Premium");
objWACC.OtherPr = Convert.ToDouble(nodeWACCTmp[0].LastChild.InnerText);
nodeWACCTmp = xmlWACCSummary.GetElementsByTagName("Lending_Rate_Premium");
objWACC.LendRatePr = 100 * Convert.ToDouble(nodeWACCTmp[0].LastChild.InnerText);
nodeWACCTmp = xmlWACCSummary.GetElementsByTagName("WACC");
objWACC.FairValue = Convert.ToDouble(nodeWACCTmp[0].LastChild.InnerText);
}
return View(objWACC);
}
Here is the View:
<div class="content" style="width:1000px">
<p><input id="text_tag_input" class="form-control input-sm" type="text"></p>
<br />
<div>
<table id="tbl_posts">
<tbody id="tbl_posts_body">
<tr id="rec-1">
#*BW: These is the dummy data for the keywords selection, when the sql is ready to linked to the model. These will be deleted*#
#{
Model.KeywordOptions = new List<SelectListItem>();
Model.KeywordOptions.Add(new SelectListItem
{
Text = "--Select Option--",
Value = "selectoption1",
});
Model.KeywordOptions.Add(new SelectListItem
{
Text = "Market Cap".ToString(),
Value = "TEST 1",
});
Model.KeywordOptions.Add(new SelectListItem
{
Text = "Revenue",
Value = "TEST 2"
});
Model.KeywordOptions.Add(new SelectListItem
{
Text = "Keywords",
Value = "TEST 3"
});
}
#{
Model.MarketandRevenueOptions = new List<SelectListItem>();
Model.MarketandRevenueOptions.Add(new SelectListItem
{
Text = "--Select Option--",
Value = "",
});
Model.MarketandRevenueOptions.Add(new SelectListItem
{
Text = "Greater Than",
Value = "Test 4",
});
Model.MarketandRevenueOptions.Add(new SelectListItem
{
Text = "Less Than",
Value = "Test 5"
});
Model.MarketandRevenueOptions.Add(new SelectListItem
{
Text = "Equals",
Value = "Test 6"
});
Model.MarketandRevenueOptions.Add(new SelectListItem
{
Text = "Range",
Value = "Test 7"
});
}
#{
Model.KeywordsList = new List<SelectListItem>();
Model.KeywordsList.Add(new SelectListItem
{
Text = "--Select Option--",
Value = "Test 8",
});
Model.KeywordsList.Add(new SelectListItem
{
Text = "Excluding",
Value = "Test 9",
});
Model.KeywordsList.Add(new SelectListItem
{
Text = "Including",
Value = "Test 10"
});
Model.KeywordsList.Add(new SelectListItem
{
Text = "Exact Phrase",
Value = "Test 11"
});
}
<td>#Html.DropDownListFor(model => model.KeywordOptionsSelected, Model.KeywordOptions, new { #id = "Dropdown_TEST" })</td>
<td class="display" style="display:none; text-align:left; width:18px;">#Html.DropDownListFor(model => model.MarketandRevenueOptionsSelected, Model.MarketandRevenueOptions, new { #id = "platt" })</td>
<td class="display_1" style="display:none; text-align:left; width:18px;">#Html.DropDownListFor(model => model.KeywordsListSelected, Model.KeywordsList, new { #id = "platt2" })</td>
<td class="display_2" style="display:none; text-align:center;">
<div>
<input type="number" name="keywordtextbox" value="0">
</div>
</td>
<td class="display_3" style="display:none; text-align:left;">
<div style="text-align:center;">
<input type="text" name="keywordtextbox" placeholder="e.g Toy Manufacturing">
</div>
</td>
<td><a class="btn btn-xs delete-record" data-id="1"><i class="glyphicon glyphicon-trash"></i></a></td>
</tr>
</tbody>
</table>
<div style="display:none;">
<table id="sample_table">
<tr id="">
<td>
<select required id="Dropdown_clone">
<option value="selectoption_clone">--Select Option--</option>
<option class="cont" value="clone 1"> Market Cap</option>
<option class="cont_1" value="clone 2"> Revenue</option>
<option class="cont_2" value="clone 3"> Keywords</option>
</select>
</td>
<td class="display_clone" style="display:none;">
<select required id="platt_clone">
<option value="">--Select Option--</option>
<option value="clone 4"> Greater Than </option>
<option value="clone 5"> Less Than </option>
<option value="clone 6"> Equals </option>
<option value="clone 7"> Range </option>
</select>
</td>
<td class="display_1_clone" style="display:none; text-align:left; width:10px">
<select required id="platt2_clone">
<option value="clone 8">--Select Option--</option>
<option value="clone 9">Excluding</option>
<option value="clone 10">Including</option>
<option value="clone 11">Exact Phrase</option>
</select>
</td>
<td class="display_2_clone" style="display:none;">
<div style="text-align:right;">
<input type="number" name="keywordtextbox" value="0">
</div>
</td>
<td class="display_3_clone" style="display:none;">
<div style="text-align:center;">
<input type="text" name="keywordtextbox" placeholder="e.g Toy Manufacturing">
</div>
</td>
<td><a class="btn btn-xs delete-record" data-id="0"><i class="glyphicon glyphicon-trash"></i></a></td>
</tr>
</table>
</div>
<div>
<a class="btn btn-primary pull-right add-record" data-added="0"><i class="glyphicon glyphicon-plus"></i> Add Row</a>
</div>
<br />
<br />
<form>
<input type="submit" class="waccbuttonsubmit" value='Apply' />
</form>
</div>
Follow below technique in which populate your SelectList from your controller. Its simple and clean:
Model
public string KeywordOptionsSelected { get; set; }
public SelectList KeywordOptions { get; set; }
Controller
model.KeywordOptions = new SelectList(new List<SelectListItem> {
new SelectListItem { Value = "TEST 1", Text = "Market Cap" },
new SelectListItem { Value = "TEST 2", Text = "Revenue" },
}, "Value", "Text");
View
#Html.DropDownListFor(model => model.KeywordOptionsSelected, Model.KeywordOptions, "--Select Option--", new { #id = "Dropdown_TEST" })
In this way, the code is easy to understand and View is also clean as all SelectList will be populated from cs.
You can make it more cleaner by populating SelectLists separately in methods and call in model.KeywordOptions to populate it.
public static List<SelectListItem> GetKeywords()
{
var keyword = new List<SelectListItem>();
keyword.Add(new SelectListItem { Value = "TEST 1", Text = "Market Cap" });
keyword.Add(new SelectListItem { Value = "TEST 2", Text = "Revenue" });
return keyword;
}
model.KeywordOptions = new SelectList(GetKeywords(), "Value", "Text");
I need help to get a solution to a question. The case is as follows:
We are working on a group project with asp.net, c #, javascript, html and razor technologies.
The structure of projects within the solution is as follows:
1.POJO-entities: where the models are located.
2.DataAccess: it is divided into three folders: 1. Crud (where are the classes that contain the "crudfactory" of each Pojo, 2. Dao (find the connection to the database, in this case SQL Server) and finally, the Mapper
3.CoreApi, where are the managers of each well.
4.WebApi, where are the controllers of each well.
5.WepApp, where is the UI (cshtmls) and javascripts.
Now, I have to implement a virtual wallet that can be topped up via PayPal and I have a method that receives the price and the description of the payment, for now it is "burned", but it must be parameterizable. I want to know if I can take the value of CtrlInput and put it in the HTMLAtributes of my ActionLink.
The idea may remove the # Html.ActionLink and leave the functionality in the "Update", but I don't know how to send the parameters from the view JS to the PayPal controller.
This is the javascript code for the wallet view:
function vMonedero() {
//this.tblMonederoId = 'tblMonedero';
this.service = 'monedero';
this.ctrlActions = new ControlActions();
this.columns = "IdUsuario, IdMonedero, Monto";
this.paypal = new PaymentWithPayPal();
this.RetrieveAll = function () {
this.ctrlActions.FillTable(this.service, this.tblMonedero, false);
}
this.Create = function () {
var monederoData = {};
monederoData = this.ctrlActions.GetDataForm('frmEdition');
if (monederoData["Monto"] == "") {
this.ctrlActions.ShowMessage('E', "Favor ingresar el nuevo valor");
}
else if (isNaN(monederoData["Monto"])) {
this.ctrlActions.ShowMessage('E', "Favor ingresar un valor numérico");
}
else {
this.ctrlActions.PostToAPI(this.service, monederoData);
}
}
this.Update = function () {
var monederoData = {};
monederoData = this.ctrlActions.GetDataForm('frmEdition');
price = monederoData["Monto"];
paypal.PaymentWithPayPal(price, "Recarga de monedero");
//Hace el post al create
this.ctrlActions.PutToAPI(this.service, monederoData);
//Refresca la tabla
}
this.Delete = function () {
var monederoData = {};
monederoData = this.ctrlActions.GetDataForm('frmEdition');
//Hace el post al create
this.ctrlActions.DeleteToAPI(this.service, monederoData);
//Refresca la tabla
}
this.BindFields = function (data) {
this.ctrlActions.BindFields('frmEdition', data);
}
}
//ON DOCUMENT READY
$(document).ready(function () {
var vmonedero = new vMonedero();
//vmonedero.RetrieveAll();
});
This is the view code:
#using WebApp.Helpers;
<script src="~/Scripts/Views/vMonedero.js"></script>
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="card border-secondary" style="margin-top: 50px;">
<div class="card-header">
<div class="row pull-right">
<div class="col-md-8">Monedero</div>
<div class="col-md-4">
#Html.CtrlButton(viewName: "vMonedero", id: "btnCreate", label: "Crear", onClickFunction: "Create", buttonType: "success")
#Html.CtrlButton(viewName: "vMonedero", id: "btnUpdate", label: "Recargar", onClickFunction: "Update", buttonType: "info")
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-6">
<div class="bs-component">
<form id="frmEdition">
#Html.CtrlInput(id: "txtIdUsuario", type: "text", label: "N° de identificación", columnDataName: "IdUsuario")
#Html.CtrlInput(id: "txtIdMonedero", type: "text", label: "N° de monedero", columnDataName: "IdMonedero")
#Html.CtrlInput(id: "txtIdMonto", type: "text", label: "Monto", columnDataName: "Monto")
#* #Html.CtrlDropDown(id: "drpGender", label: "Gender", listId: "LST_GENERO")*#
</form>
</div>
</div>
</div>
</div>
</div>
#*<script>
$('#price').click(function () {
var monederoData = {};
ctrlActions = new ControlActions();
ctrlActions.GetDataForm('frmEdition');
monederoData["Monto"] = price;
return price;
});
</script>*#
Paypal Controller Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PaymentPayPal.Models;
using PayPal.Api;
namespace WebApp.Controllers
{
public class PayPalController : Controller
{
// GET: PayPal
public ActionResult Index()
{
return View();
}
public ActionResult PaymentWithPaypal(string price, string product)
{
//getting the apiContext as earlier
APIContext apiContext = ConfigurationPayPal.GetAPIContext();
try
{
string payerId = Request.Params["PayerID"];
if (string.IsNullOrEmpty(payerId))
{
string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority +
"/Paypal/PaymentWithPayPal?";
var guid = Convert.ToString((new Random()).Next(100000));
var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid, price, product);
var links = createdPayment.links.GetEnumerator();
string paypalRedirectUrl = null;
while (links.MoveNext())
{
Links lnk = links.Current;
if (lnk.rel.ToLower().Trim().Equals("approval_url"))
{
paypalRedirectUrl = lnk.href;
}
}
Session.Add(guid, createdPayment.id);
Console.WriteLine(createdPayment.id);
return Redirect(paypalRedirectUrl);
}
else
{
var guid = Request.Params["guid"];
Console.WriteLine("Session:" + Session[guid] as string);
var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
if (executedPayment.state.ToLower() != "approved")
{
return View("FailureView");
}
}
}
catch (Exception ex)
{
return View("FailureView");
}
return View("SuccessView");
}
private PayPal.Api.Payment payment;
private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
{
var paymentExecution = new PaymentExecution() { payer_id = payerId };
this.payment = new Payment() { id = paymentId };
return this.payment.Execute(apiContext, paymentExecution);
}
private Payment CreatePayment(APIContext apiContext, string redirectUrl, string price, string product)
{
var itemList = new ItemList() { items = new List<Item>() };
itemList.items.Add(new Item()
{
name = product,
currency = "USD",
price = price,
quantity = "1",
sku = "sku"
});
var payer = new Payer() { payment_method = "paypal" };
var redirUrls = new RedirectUrls()
{
cancel_url = redirectUrl,
return_url = redirectUrl
};
// similar as we did for credit card, do here and create details object
var details = new Details()
{
tax = "1",
shipping = "1",
subtotal = price
};
// similar as we did for credit card, do here and create amount object
var amount = new Amount()
{
currency = "USD",
total = "" + (int.Parse(price) + 1 + 1), // Total must be equal to sum of shipping, tax and subtotal.
details = details
};
var transactionList = new List<Transaction>();
transactionList.Add(new Transaction()
{
description = "Transaction description.",
invoice_number = Convert.ToString((new Random()).Next(100000)),
amount = amount,
item_list = itemList
});
this.payment = new Payment()
{
intent = "sale",
payer = payer,
transactions = transactionList,
redirect_urls = redirUrls
};
// Create a payment using a APIContext
return this.payment.Create(apiContext);
}
}
}
While binding the List of values from GET method the WebGrid is displaying the data and same is not displaying in POST method.
Controller:
[HttpGet]
public ActionResult Index()
{
ObservableCollection<Product> inventoryList = new ObservableCollection<Product>();
inventoryList.Add(new Product { Id = "P101", Name = "Computer", Description = "All type of computers", Quantity = 800 });
inventoryList.Add(new Product { Id = "P102", Name = "Laptop", Description = "All models of Laptops", Quantity = 500 });
inventoryList.Add(new Product { Id = "P103", Name = "Camera", Description = "Hd cameras", Quantity = 300 });
inventoryList.Add(new Product { Id = "P104", Name = "Mobile", Description = "All Smartphones", Quantity = 450 });
inventoryList.Add(new Product { Id = "P105", Name = "Notepad", Description = "All branded of notepads", Quantity = 670 });
inventoryList.Add(new Product { Id = "P106", Name = "Harddisk", Description = "All type of Harddisk", Quantity = 1200 });
inventoryList.Add(new Product { Id = "P107", Name = "PenDrive", Description = "All type of Pendrive", Quantity = 370 });
return View(inventoryList);
}
[HttpPost]
public ActionResult Reports(string name)
{
ObservableCollection<Product> inventoryList = new ObservableCollection<Product>();
inventoryList.Add(new Product { Id = "P101", Name = "Computer", Description = "All type of computers", Quantity = 800 });
inventoryList.Add(new Product { Id = "P102", Name = "Laptop", Description = "All models of Laptops", Quantity = 500 });
inventoryList.Add(new Product { Id = "P103", Name = "Camera", Description = "Hd cameras", Quantity = 300 });
inventoryList.Add(new Product { Id = "P104", Name = "Mobile", Description = "All Smartphones", Quantity = 450 });
inventoryList.Add(new Product { Id = "P105", Name = "Notepad", Description = "All branded of notepads", Quantity = 670 });
inventoryList.Add(new Product { Id = "P106", Name = "Harddisk", Description = "All type of Harddisk", Quantity = 1200 });
inventoryList.Add(new Product { Id = "P107", Name = "PenDrive", Description = "All type of Pendrive", Quantity = 370 });
return View(inventoryList);
}
View:
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.NextPrevious);}
<div id="gridContent">
#grid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
grid.Column("Id", format: (item) => item.GetSelectLink(item.Id)),
grid.Column("Name", " Name"),
grid.Column("Description", "Description", style: "description"),
grid.Column("Quantity", "Quantity")
))
</div>
Can someone help me in this?
In a view I'm using 3 dropdownlist strongly-typed to a model like this:
#using (Html.BeginForm())
{
<p>Filter by rarity: #Html.DropDownListFor(_item => _item.mRarity, Model.mRarityList, new {#id = "cardRarity"})
Filter by type: #Html.DropDownListFor(_item => _item.mType, Model.mTypeList, new {#id = "cardType"})
Filter by color: #Html.DropDownListFor(_item => _item.mColor, Model.mColorList, new {#id = "cardColor"})
</p>
}
Here's the view in which the thing is displayed:
#model PagedList.IPagedList<MvcMagicAdmin.Utilities.CardDisplay>
#{
ViewBag.Title = "Cards Display Results";
}
<h2>
Cards Display Results
</h2>
<script type="text/javascript">
$(document).ready(function () {
$('#cardRarity').change(function () {
var showCardRarity = $(this).val();
alert(showCardRarity);
var showCardType = $('#cardType').val();
var showCardColor = $('#cardColor').val();
refreshResults(showCardRarity, showCardType, showCardColor);
});
$('#cardType').change(function () {
var showCardType = $(this).val();
alert(showCardType);
var showCardRarity = $('#cardRarity').val();
var showCardColor = $('#cardColor').val();
refreshResults(showCardRarity, showCardType, showCardColor);
});
$('#cardColor').change(function () {
var showCardColor = $(this).val();
alert(showCardColor);
var showCardRarity = $('#cardRarity').val();
var showCardType = $('#cardType').val();
refreshResults(showCardRarity, showCardType, showCardColor);
});
function refreshResults(rarity, type, color) {
$.get("#Url.Action("DisplayCardsResults", "Card")", {
_page: 1,
_sortOrder: "#ViewBag._sortOrder",
_rarity: rarity,
_type: type,
_color: color,
}, function(data) {
$("#resultsDiv").html(data);
});
}
});
</script>
<div>
<div class="float-left">
<p>#Html.ActionLink("Make a new search", "SearchCardsAdvanced")</p>
</div>
<div class="float-right">
<p><span class="bold baseFontSize">Legend: </span>Details #Html.Image("~\\Images\\Functional\\Icons\\detailsIcon.jpg", "details", new { #class = "centerVert" } )
Edit #Html.Image("~\\Images\\Functional\\Icons\\editIcon.png", "edit", new {#class = "centerVert"} )
Delete #Html.Image("~\\Images\\Functional\\Icons\\trashIcon.png", "delete", new {#class = "centerVert"} )</p>
</div>
<div class="clear"></div>
</div>
#{
Html.RenderAction("FilterCardsResults", "PartialViews");
}
<div id="resultsDiv">
#{
Html.RenderPartial("ResultsTable", Model);
}
</div>
So, yes, I am calling a partial view from another controller because I pass a model which is not included in the Original List of models.
The view is generated like this:
private static readonly CardsFilters mCardsFilters = new CardsFilters();
public ActionResult FilterCardsResults()
{
return PartialView("Filters/FilterCardsResults", mCardsFilters);
}
Here's the model on which the data is built:
public class CardsFilters
{
public string mRarity { get; set; }
public IEnumerable<SelectListItem> mRarityList { get; set; }
public string mType { get; set; }
public IEnumerable<SelectListItem> mTypeList { get; set; }
public string mColor { get; set; }
public IEnumerable<SelectListItem> mColorList { get; set; }
public CardsFilters()
{
List<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem() {Value = "All", Text = "All"},
new SelectListItem() {Value = "Land", Text = "Land"},
new SelectListItem() {Value = "Common", Text = "Common"},
new SelectListItem() {Value = "Uncommon", Text = "Uncommon"},
new SelectListItem() {Value = "Rare", Text = "Rare"},
new SelectListItem() {Value = "Mythic Rare", Text = "Mythic Rare"},
new SelectListItem() {Value = "Special", Text = "Special"}
};
mRarityList = new SelectList(items, "Value", "Text");
items = new List<SelectListItem>
{
new SelectListItem(){ Value = "All", Text = "All"},
new SelectListItem(){ Value = "Artifact", Text = "Artifact"},
new SelectListItem(){ Value = "Instant", Text = "Instant"},
new SelectListItem(){ Value = "Creature", Text = "Creature"},
new SelectListItem(){ Value = "Land", Text = "Land"},
new SelectListItem(){ Value = "Planeswalker", Text = "Planeswalker"},
new SelectListItem(){ Value = "Enchantment", Text = "Enchantment"},
new SelectListItem(){ Value = "Sorcery", Text = "Sorcery"},
new SelectListItem(){ Value = "Tribal", Text = "Tribal"},
};
mTypeList = new SelectList(items, "Value", "Text");
items = new List<SelectListItem>
{
new SelectListItem(){ Value = "All", Text = "All"},
new SelectListItem(){ Value = "White", Text = "White"},
new SelectListItem(){ Value = "Red", Text = "Red"},
new SelectListItem(){ Value = "Green", Text = "Green"},
new SelectListItem(){ Value = "Blue", Text = "Blue"},
new SelectListItem(){ Value = "Black", Text = "Black"},
new SelectListItem(){ Value = "Gold", Text = "Gold"},
new SelectListItem(){ Value = "Colorless", Text = "Colorless"},
};
mColorList = new SelectList(items, "Value", "Text");
}
}
And, finally, the post method called in the controller:
public ActionResult DisplayCardsResults(int? _page, string _sortOrder, string _rarity = "", string _type = "", string _color = "")
{
ViewBag._rarity = _rarity;
ViewBag._color = _color;
ViewBag._type = _type;
if (Request.HttpMethod != "GET")
{
_page = 1;
}
if (mListCards.Count == 0)
{
TempData[MessageDomain.Tags.TEMPDATA_MESSAGE_ERROR] = NODATAFILTERERRORMESSAGE;
}
int pageNumber = (_page ?? 1);
if (Request.IsAjaxRequest())
{
mListCardsToShow = GetListCardsToShow(_rarity, _color, _type);
return PartialView("ResultsTable", mListCardsToShow.ToPagedList(pageNumber, ValueDomain.PAGE_SIZE));
}
if (mListCardsToShow.Count > 0)
{
mListCardsToShow = SortListOrder(_sortOrder, mListCardsToShow);
return View(mListCardsToShow.ToPagedList(pageNumber, ValueDomain.PAGE_SIZE));
}
if (mListCards.Count > 0)
{
mListCards = SortListOrder(_sortOrder, mListCards);
}
return View(mListCards.ToPagedList(pageNumber, ValueDomain.PAGE_SIZE));
}
The dropdownlist works very fine, except for one reason. When I post back the form, all the values selected in the dropdownlist resets to "All", and I'd like to keep them selected. How might I do this?
You must make shure that you are correctly binding your return model into the view.
I took your example and included it into a simple project, that is working ok:
The controller with a simple POST:
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
var model = new CardsFiltersViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(CardsFiltersViewModel model)
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View(model);
}
public ActionResult About()
{
return View();
}
}
It returns the object the you presented above.
The View is the exact same as your code.
#using (Html.BeginForm())
{
<p>
Filter by rarity: #Html.DropDownListFor(_item => _item.mRarity, Model.mRarityList, new { #id = "cardRarity" })
Filter by type: #Html.DropDownListFor(_item => _item.mType, Model.mTypeList, new { #id = "cardType" })
Filter by color: #Html.DropDownListFor(_item => _item.mColor, Model.mColorList, new { #id = "cardColor" })
</p>
<input type="submit" name="name" value=" " />
}
With the reference to the model class object (
#model MvcApplication7.Controllers.CardsFiltersViewModel
)