Getting 30+ dropdowns values to the controller to update model- MVC3 C# - c#

I have a very large form that represents a month or more of data. Each day has 3 drop-downs the user can update and then i need to save the data in the form. I should mention I had to make a custom dropdown (HERE) to use a style class so it's not the standard Html.dropdown()
So what I'd like to do is something like...
View:
#{
List<string> DropdownValues = new List<string>();
}
#using(Html.BeginForm("Method","Controller",FormMethod.Post,new{ Data = DropdownValues}))
{
#Html.CustomDropdown("Name1",ListOfOptions1)
#Html.CustomDropdown("Name2",ListOfOptions2)
#Html.CustomDropdown("Name3",ListOfOptions3)
<input type="submit" value="Submit" />
#{
//Do on submit
DropdownValues.add(Name1.value);
DropdownValues.add(Name2.value);
DropdownValues.add(Name3.value);
}
}
Ideas?
Thanks!

You can access form element direct from controller code without them having to be part of the Action parameters. Maybe this is what you are looking for?...
//In controller post action
string name1 = Request.Form["Name1"];
string name2 = Request.Form["Name2"];
//etc...
You could even put it in a loop depending on what you are doing with the data...
for(int i = 1; i <= 30; i++)
{
string nameX = Request.Form["Name" + i];
}

Related

Returning a string of selected values from a checkbox collection

I am building a C# MVC view that includes a field with a series of 4 checkboxes. I can populate the list with the values and return individual values just fine, so the basics of the form appear to work. Here is how the options get populated on the view:
#for (int i = 0; i < Model.QuesOptions.Count; i++)
{
<div>
#Html.HiddenFor(x => x.QuesOptions[i].Name)
#Html.CheckBoxFor(x => x.QuesOptions[i].Checked)
#Html.LabelFor(x => x.QuesOptions[i].Checked, Model.QuesOptions[i].Name)
</div>
}
The ultimate goal is to return a single list of values (ideally comma delimited) of the values of each item checked at at the time of posting. So when the user clicks "submit" on the form, it would be great if a single field on the view model (called "UserAnswer") would populate with a comma delimited string. Is this even possible right on the view model?
I had hopes, probably empty ones, that some variation of this would work:
#Html.HiddenFor(model => model.Ques.UserAnswer,
new { Value = Model.QuesOptions.Where(x=>x.Checked).Select(x=>x.Name) })
Or would this be a job for some kind of extension method or HTML helper?
Finding no way to process comma delimited strings within Razor itself (a way may exist, but I haven't found it), I instead opted for JavaScript. The following code inserts comma delimited lists into hidden fields on the view model:
function submitForm() {
var question2 = "";
for (i = 0; i <= 3; i++) {
var trueOrNo = document.getElementById('Quez2Options_' + i + '__Checked').checked;
if (trueOrNo) {
question2 += document.querySelector('label[for="Quez2Options_' + i + '__Checked"]').innerHTML + ",";
}
}
document.getElementById('Quez2_UserAnswer').value = question2.substring(0, question2.length - 1);
var val3a = document.getElementById('Quez3a').value;
var val3b = document.getElementById('Quez3b').value;
var val3c = document.getElementById('Quez3c').value;
var question3 = val3a + "," + val3b + "," + val3c;
document.getElementById('Quez3_UserAnswer').value = question3;
}

passing a session variable in link created by for loop C#

I have a page reading an api thats giving a list of ID's.
I then want that to create a link that then sends that ID to another API to get that individual object.
I've got the pages working manually but now trying to send the data between them is the issue.
My current code is this
#{
for (var i = 0; i < Model.records.Count; i++)
{
string currID = Model.records[i].ID;
<td>#Html.ActionLink(Model.records[i].ID, "Game", "Home", Session["game"] = currID)</td>
<td>#Model.records[i].GameName</td>
<td>#Model.records[i].Player1</td>
<td>#Model.records[i].Player2</td>
<td></td><br />
}
}
What this does, And I understand Why, is pass the final record's ID to the api, and always gives me that result, as i is the final value at that point.
how can I tell the link that it needs to keep it's iteration of i and pass that value?
With this expression,
Session["game"] = currID
You are actually updating the Session item value within the loop for each iteration with the current value of currID.
If you want to send the Session item value as querysting/route values, you may use the overload which takes 5 params. The fourth parameter is an anonymous object where you will specify the key and values, these key and values will be used to generate the URL.
For example, the below code will add the gameId querystring item and it's value will be the value stored in Session["game"]
#{
var game = Session["game"];
for (var i = 0; i < Model.records.Count; i++)
{
string currID = Model.records[i].ID;
<td>#Html.ActionLink(Model.records[i].ID, "Game", "Home",
new { gameId = game }, null)</td>
<td>#Model.records[i].GameName</td>
}
}
Assuming your Game action method has a parameter with name gameId
public ActionResult Game(string gameId)
{
// to do : Return something
}
If you want to send the currID as well, pass that too
#Html.ActionLink(Model.records[i].ID, "Game", "Home",
new { gameId = game, currId = currID }, null)
The fifth parameter( where I passed null) is for htmlAttributes which will be used to add other HTML attributes to the element rendered by this helper (Ex : If you want to add a CSS classs etc)

C# mvc5 add Textbox by Controller

is it possible to add a texbox by controller to a View?
I have a dynamic number of textboxes and need a way to add this by the Controller to the View. Is this Possible?
Do Something like this. Just a quick written code. Might be syntax errors.
DynamicTextBoxCreation.cs
public class DynamicTextBoxCreation
{
public List<string> textBoxList;
public ActionResult DynamicTextBox()
{
/* Fill your dynamic list here from DB or from any other logic */
return textBoxList;
}
}
DynamicTextBox.cshtml
#model DynamicTextBoxCreation;
#code{
var i = 1;
}
foreach(var tbItem in textBoxList)
{
#Html.TextBox(' + tbItem + i + ', "", new {#class = "css-class", #onclick = "alert('demo');"});
i += 1;
}

ASP.net MVC 5 Razor dropdown box

Hey all I am new to Razor MVC and wanted to make a select box that has the past 10 years listed inside it (2016, 2015, 2014, etc....).
This is my current Controllers code:
public ActionResult loadPast10Years()
{
List<int> last10Years = new List<int>();
int currentYear = DateTime.Now.Year;
for (int i = currentYear - 10; i < currentYear; i++)
{
last10Years.Add(i);
}
ViewBag["last10Years"] = last10Years;
return View();
}
And my Razor code:
#Html.DropDownList("last10Years", (SelectList)ViewBag["last10Years"], "--Select One--")
But I have an error when loading the page that says:
InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key 'last10Years'.
So... What am I missing?
This is how I would do it in the view
#Html.DropDownList("Last Ten Years", (IEnumerable<SelectListItem>)ViewBag.LastTenYears, "Select A Year")
and in your Action
List<int> last10Years = new List<int>();
int currentYear = DateTime.Now.Year;
for (int i = currentYear - 10; i < currentYear; i++)
{
last10Years.Add(i);
}
ViewBag.LastTenYears = new SelectList(last10Years);
You can see a demo here
Following from your comment please find below my updated answer.
I would first create a Model class which we will be using in our view. In this model class you can have your appropriate properties. For now we're only going to be using SelectlistItem
so our class will look like
public class ViewModel
{
public IEnumerable<SelectListItem> LastTenYears { get; set; }
}
Then in our controller we can create a method which will provide us the information for our drop down.
public IEnumerable<SelectListItem> GetLastTenYears()
{
List<SelectListItem> ddl = new List<SelectListItem>();
int currentYear = DateTime.Now.Year;
for (int i = currentYear - 10; i < currentYear; i++)
{
ddl.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });
}
IEnumerable<SelectListItem> lastTenYears = ddl;
return lastTenYears;
}
Now we want to pass this data to the view. For argument sake I will use Index as a view but you can pass it to whatever view you like. So we will change our Index action to
public ActionResult Index()
{
ViewModel viewModel = new ViewModel();
viewModel.LastTenYears = GetLastTenYears(); //get the drop down list
return View(viewModel); //we're passing our Model to the view
}
Finally, we want to make sure our view knows which Model to use so we will do the following the beging of the Index.cshtml file
#model YourNameSpace.ViewModel
and our DropDownList helper method will now change to point to the property in our Model class as
#Html.DropDownList("Last Ten Years", Model.LastTenYears, "Please select a year")
There are few issue in your code right now.
Don't name the ViewBag key same as the DropDownList name, they don't
work well together, you can change the ViewBag Key name to something like last10YearsOptionsinstead oflast10Years`, so that it is different than control name.
You have not create SelectList in controller before adding to ViewBag, but you are casting it to SelectList in View.
In ViewBag values are stored like ViewBag.SomeKey= "SomeValue", but you are doing it wrong way.
After Fixing the above problems your code will look like :
ViewBag.last10YearsOptions = last10Years.Select(x => new SelectListItem()
{
Text = x.ToString(),
Value = x.ToString()
}
);
and then in View:
#Html.DropDownList("last10Years",
"--Select One--",
ViewBag.last10YearsOptions as IEnumerable<SelectListItem>,
null )
ViewBag is not a dictionary with key value pairs.
also DropDownList works with ICollection ithink
so this code works form
#Html.DropDownList("last10Years", new SelectList(ViewBag.last10YearsOptions), "Select one from here")
Controller is here;
public ActionResult loadPast10Years()
{
List<int> last10Years = new List<int>();
int currentYear = DateTime.Now.Year;
for (int i = currentYear - 10; i < currentYear; i++)
{
last10Years.Add(i);
}
ViewBag.last10Years = new SelectList(last10Years);
return View();
}
And View
#Html.DropDownList("last10Years", "--Select One--")

How to retrieve in a variable the result of a query to export it in pdf?

I'll explain a quiet better here. I've this method wich returns me some lines of ma table according to a searchstring I informed in my textbox.
public ActionResult Index(string site, string searchString)
{
var user = from m in db.OrderDetails
select m;
if (!String.IsNullOrEmpty(searchString))
{
user = user.Where(s => s.Order.ClientID.Contains(searchString));
}
if (!String.IsNullOrEmpty(site))
{
user = user.Where(c => c.Order.SiteNumber.Contains(site));
}
return View(user);
}
In the same class, I've an other method which generate a pdf file (all the backend process is set up in a second project include in the first).
public ActionResult PrintOrders()
{
var user = from m in db.OrderDetails
select m;
return this.ViewPdf("Facture", "PrintView", user);
}
This second method, when it generate my pdf file, displays all the entries of my table. I would like that, when I click on my link (on the same page view wich display my table entries) for generate my pdf file, if I did a search before, I juste have fields that match my searchstring (or site string).
How can I implement it ? There is a way do to it ?
Thanks for your help, and sorry for the title which is maybe not too relevant. Also sorry for my english, hope you'll understand my aim.
EDIT INFORMATIONS
After looking, when I set up my PrintOrders() method like my Index() method as follow :
public ActionResult PrintOrders(string searchString, string username)
{
var user = from m in db.OrderDetails select m;
if (!String.IsNullOrEmpty(searchString))
{
user = user.Where(s => s.Order.ClientID.Contains(searchString));
}
if (!String.IsNullOrEmpty(site))
{
user = user.Where(c => c.Order.SiteNumber.Contains(site));
}
return this.ViewPdf("Facture Krys-Group", "PrintView", user);
}
and set my view like this :
#using (Html.BeginForm("PrintOrders", "Historic", FormMethod.Get))
{
Seach by ID : #Html.TextBox("searchString")
Search by Site : #Html.TextBox("site")
<input type="submit" value="Search" /></p>
}
then it works. But I've already the same form in my view for "Index" instead of "PrintOrders". How can I combine both ?
I am not sure I follow you completely but I think you achieve what you are looking for with the use of partial views. The form you mention can be a partial view that gets rendered into the pdf view and like that you really have one form but displayed in both pages. Hopefully I understood what you were after and this helps you.

Categories

Resources