ASP MVC Dropdown - asp.net

Please look at my code. I am trying to display some dynamic customers in the dropdown menu. And after selecting a customer button is pressed. Then products owned by the selected customer should be displayed in the textarea. But the problem is that after selecting a customer and pressing the button, nothing is displayed in the text area !. As i am new to ASP MVC can you help me out this problem?
Controller class-------------------->
public class ProductsController : Controller
{
CandidateEntities db;
public ProductsController()
{
db = new CandidateEntities();
}
public ActionResult Index()
{
ViewData["Customers"] = new SelectList(db.Customer.ToList(), "CustomerId", "Firstname");
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection form)
{
int customerId = int.Parse(form["Customers"]);
var cust = db.Customer.First(x=>x.CustomerId == customerId);
var Query =
from customer in db.Customer
join prod in db.Products on customerId equals prod.Customer.CustomerId
select prod;
ViewData["Products"] = Query.ToString();
return View("Index");
}
}
Index view------------------>
Index
<%using(Html.BeginForm()){ %>
<%=Html.DropDownList("Customers", "Seletc one")%>
<input type="submit" value="Click !" />
<%=Html.TextArea("Textarea", ViewData["Products"]) %>
<%} %>

Are you sure your query is returning results? It seems to be querying for every product for every customer, it might be rewritten something like:
from product in db.Prodcuts
where product.Customer.CustomerID = customerId
select product
Also, (and it depends on your code), but is calling ToString on a list of Product objects going to return what you want?

db.Products.Where(p => p.CustomerId == cust)
or
db.Customer.Find(cust).Products

Related

How can I add a value derived from query to database on [HttpPost]

I have a modal popup used to update my form. There is a db field that is dependent upon the selection of another value on a popup. I would like to post that value to my form. Note that value is not on my popup. The ViewBag has the value I need but it is not in catalogPrice.
Help would be very much appreciated. Thanks.
[HttpPost]
public IActionResult AddCatalogPrice(CatalogPrice catalogPrice)
{
if (ModelState.IsValid)
{
var newNDCDescription = catalogPrice.NDCDescription;
var getNDC = (from n in Db.NationalDrugCodes
where n.NDCDescription == newNDCDescription
select new { n.NDCNumber }).ToList();
ViewBag.getNDC = getNDC;
Db.CatalogPrices.Add(catalogPrice);
Db.SaveChanges();
}
return RedirectToAction("ModalPopupCatalogPrice", "GTN");
}

asp.net mvc form includes for loop over form controllers

i want to submit a form with for loop inside of it that loops over the form controllers since i want to pass list of model into a post method action in such a way that each and every form controller ( TextBoxFor ) is populated by corresponding value of my list of model
my Model :
public class ExcelRowData
{
public string LastName { get; set; }
public string FirstName { get; set; }
public string Score { get; set; }
public string EnrollmentTime { get; set; }
public string GraduationTime { get; set; }
}
and this is my view :
#model List<NewTest.Models.ExcelRowData>
#using (Html.BeginForm("Delete", "MyTest", FormMethod.Post))
{
for (var i = 0 ; i < Model.Count ; i++)
{
<tr>
<td>#Html.TextBoxFor(p => Model[i].LastName)</td>
<td>#Html.TextBoxFor(p => Model[i].FirstName)</td>
<td>#Html.TextBoxFor(p => Model[i].Score)</td>
<td>#Html.TextBoxFor(p => Model[i].EnrollmentTime)</td>
<td>#Html.TextBoxFor(p => Model[i].GraduationTime)</td>
<td><input type="submit" formaction="#Url.Action("Delete", "MyTest", new {Ln = Model[i].LastName})" value="Delete"/></td>
</tr>
}
}
i populated my model from excel file then i show the excel data in above table in view and then there is a delete button in case of deleting a record
and in my delete action i delete the selected record by the parameter passed from submit button , after that i repopulate my model and again i pass it to the same view
this is the delete action in my controller :
[HttpPost]
public ActionResult Delete(ExcelRowData evm, string Ln)
{
var exceldata = new List<ExcelRowData>();
var del = evm.FirstOrDefault(p => p.LastName == Ln);
evm.Remove(del);
foreach (var item in evm)
{
exceldata.Add(
new ExcelRowData { LastName = item.LastName, FirstName = item.FirstName, Score = item.Score, EnrollmentTime = item.EnrollmentTime, GraduationTime = item.GraduationTime}
);
}
return View("ExcelTable", exceldata);
}
the problem is when i press delete button in any row , it delets the record from bottom of the list , it doesn't matter which row i click to delete , it deletes from bottom of the list.
You posting back the whole collection, so all the property values have been added to ModelState, and the HtmlHelper methods that generate form controls (except PasswordFor()) use the values from ModelState (if they exist) rather the the property value.
You can solve this by adding
ModelState.Clear();
before you return the view, however the correct approach is to follow the PRG (Post, Redirect Get) pattern, and redirect to your GET method.
To understand why the HtmlHelper methods use ModelState, refer this answer.
As a side note, you can improve performance by using ajax to remove the item (and if successfully deleted, remove the corresponding row from the DOM), but that means you also need to include a hidden input for the collection indexer so that you can post back non-zero/non-consecutive indexers if your also posting back the updated collection elsewhere in your view. The input would be <input type="hidden" name="Index" value = "#i" />

Convert IQueryable object to a List and add a new Item

I have the following IQueryable object:
var user = from d in _context.Users
join userRole in _context.UserRoles on d.Id equals userRole.UserId
join role in _context.Roles on userRole.RoleId equals role.Id
where role.Name == "Liquidador"
select d;
Which then is send as a ViewBag to the View:
ViewBag.UserID = new SelectList(user.AsNoTracking(), "UserName", "Name", selectedUser);
The Problem:
I need to add a new Item to the result of the IQueryable. So I've proceeded like this:
var UserNameList = user.Select(s => new { s.Name, s.UserName }).ToList();
However, I'm missing something when I'm trying to add the new item:
UserNameList.Insert(0, new *NewWhat?* { Name = "Liquidador", UserName = "--Select--"} );
Usually I declare a new element of a specific model but in this case I don't know which model to declare for this IQueryable. Any recomendations?
Thanks
EDIT:
The IQueryable object goes to the Get Method of the View as part of a function:
public async Task<IActionResult> Management()
{
PopulateUserDropDownList();
var Tiendas = await _context.Stores.ToListAsync();
StoreEmployee model = new StoreEmployee
{
Stores = Tiendas
};
return View(model);
}
This list is then presented in a dropdownlist, inside a table:
<td class="col-md-2">
<div class="form-group" form="#(String.Format("{0}{1}","form",item.StoreID))">
<div>
<select asp-for="#item.Usuario" class="form-control" asp-items="ViewBag.UserId" form="#(String.Format("{0}{1}","form",item.StoreID))"></select>
<span asp-validation-for="#item.Usuario" class="text-danger"></span>
</div>
</div>
</td>
It seems it would be cleaner if you define a class UserDTO (or any other name that likes you more)
public class UserDTO
{
public string Name { get; set; }
public string UserName { get; set; }
}
and then you do
var UserNameList = user
.Select(s => new UserDTO { Name = s.Name, UserName = s.UserName })
.ToList();
UserNameList.Insert(0, new UserDTO { Name = "Liquidador", UserName = "--Select--"} );
OTOH... smells a little to add the empty element as part of the data array, my recommendation is to handle that on razor view and just send UserNameList with real data. Dropdown razor methods contains overloads to specify the empty element text.
If you show your HTML, we may help you to implement a better solution.

ASP.Net MVC 3 ListBox Selected Items Collection Null

I have a pretty simple scenario and I'm sure I'm just missing something obvious. I'm trying to use a ListBox to grab multiple Id's and add them to my model, but no matter what I do, the collection is always null. Here's the code:
The model collections:
public IEnumerable<Model.UserProfile> TravelBuddies { get; set; }
public IEnumerable<int> SelectedTravelBuddies { get; set; }
I populate the TravelBuddies collection in my controller.
The view code:
<div class="module_content">
#if (Model.TravelBuddies.Count() > 0)
{
#Html.ListBoxFor(m => m.SelectedTravelBuddies, new MultiSelectList(Model.TravelBuddies, "Id", "FullName"))
}
else
{
<span>You don't currently have any travel buddies (people who were with you on this trip). Don't worry, you can add some to this trip later if you'd like.</span>
}
</div>
The select list is populated in my view. No problem there. But once I select multiple items and submit my form, the Model.SelectedTravelBuddies collection is always null. Am I missing something obvious? It's been a long night of coding.
Update: Added Controller Code
[HttpGet]
public ActionResult New()
{
Model.Trip trip = new Model.Trip();
ITripService tripService = _container.Resolve<ITripService>();
IUserAccountService userService = _container.Resolve<IUserAccountService>();
int userProfileId = userService.GetUserProfile((Guid)Membership.GetUser().ProviderUserKey).Id;
trip.TripTypes = new SelectList(tripService.GetTripTypes(), "Id", "Name");
trip.TravelBuddies = userService.GetTravelBuddies(userProfileId);
tripService.KillFlightLegTempStorage();
return View(trip);
}
[HttpPost]
public ActionResult New([Bind(Exclude = "TripTypes")] Model.Trip trip)
{
ITripService tripService = _container.Resolve<ITripService>();
if (!ModelState.IsValid)
{
tripService.KillFlightLegTempStorage();
return View(trip);
}
int tripId = tripService.CreateTrip(trip, (Guid)Membership.GetUser().ProviderUserKey);
tripService.KillFlightLegTempStorage();
return RedirectToAction("Details", "Trip", new { id = tripId });
}
Ok so you are binding to SelectedTravelBuddies. When your list is rendered, what is it's name? It's been a long night for me too :) want to make sure it matches the model. Also are you sure the list is in the form element so they are posted?

Getting values from an asp.net mvc dropdownlist

Can someone help me with getting values from a dropdownlist in asp.net mvc?
I can get values from textboxes,etc...but,how do I get these 2 things...
Getting Selected Item Value of the drop down list from the controller class
Getting all the list of items of the drop down list from the controller class
Thanks
You can get the selected value from a drop down list the same way as you do for text boxes.
Using default model binding
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
//MyList will contain the selected value
//...
}
or from a FormCollection
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(FormCollection form) {
string val = form["MyList"];
//...
}
or from the request
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
string val = Request.Form["MyList"]; //or
val = Request["MyList"];
//...
}
Where your drop down list is named "MyList".
<%= Html.DropDownList("MyList", MyItems) %>
or straight HTML
<select name="MyList">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
</select>
The browser will only submit the selected value from the drop down list and not all the other values. To get the list of all the other items you should invoke the code that populated the list in the first place (assuming you used Html.DropDownList()).
Update
[AcceptVerbs(Http.Get)]
public ActionResult GetValueExample() {
ViewData["MyItems"] = GetSelectList();
return View();
}
[AcceptVerbs(Http.Get)]
public ActionResult GetValueExample(string MyList) {
//MyList contains the selected value
SelectList list = GetSelectList(); //list will contain the original list of items
//...
}
private SelectList GetSelectList() {
Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("Item 1", "1");
list.Add("Item 2", "2");
list.Add("Item 3", "3");
return new SelectList(list, "value", "key");
}
//...
<%= Html.DropDownList("MyList", ViewData["MyItems"] as SelectList) %>
Well it's hard to answer correctly since you've given so little information, but in general you get the selected value in the post method of the Controller.
Something like this might explain it better:
Consider having this dropdownlist:
//instantiate the dropdownlist in the controller method.
public ActionResult Create() {
List<string> items = new List<string>() {"first", "second", "third"};
SelectList SomeSelectItems = new SelectList(items);
ViewData["list"] = SomeSelectItems;
return View();
}
<%= Html.DropDownList("DDL", (SelectList)ViewData["list"]) %>
In your controller you would get the value of the dropdownlist like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string DDL)
{
string theValue = DDL;
return View();
}
To get all the values from the dropdownlist would be the same as putting them into the selectlist in the first place. I will assume you have a method that is called to fill the dropdownlist with items. Simply call this method from within the controller and handle the values appropriately.
I think you need to rethink this. The values for the dropdown should come from the controller and sent to the view for display in the dropdown to allow the user to select. Then the page form sends the selected value back to the controller. Data should always be on the server side and the view is just for display.

Resources