Display drop down list MVC4 with many levels [duplicate] - asp.net-mvc-4

I have a table in database that has a foreign key to itself. While adding product products I want the users to be able to select a category from DropDownList. Right now, I am able to show the result like following ::
Electronics
MP3 Players
But, it would be ideal if they are shown like this, since MP3 Player is a child of Electronics :-
Electronics
MP3 Players
How can I achieve this in a DropDownList ? My current code for retrieving and displaying is following respectively :-
public ActionResult Create()
{
ViewBag.ParentCategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName");
return View();
}
CSHTML
<div class="editor-field">
#Html.DropDownList("ParentCategoryID", String.Empty)
#Html.ValidationMessageFor(model => model.ParentCategoryID)
</div>

It looks like you need optgroups. Unfortunately MVC has no native support for this. So as mentioned in the following post you can write one yourself:
ASP.Net MVC 3: optgroup support in Html.DropDownListFor

Related

Pass list from Razor page to code behind to bulk insert using Dapper

So I've created an HTML table on a Razor page as shown below. Basically I'm just calling a method that returns a list and then using a foreach to go create the rows and controls. The part I'm completely lost on is how I go about posting this data back to the server and on the code behind using that data to insert back to SQL Server. I'm using Dapper and I'd like each row of the table to represent a data row, or one object, but how do I get the data from the Razor page passed back as a list of a class? Not sure if my terminology is accurate here but can you model bind on a list of a type? Would appreciate some assistance thanks!
It seems I'm so far off track (or so few people use asp.net core and Dapper) that I'm not getting any help. But someone very helpful marked down my question without commenting - thanks so much.
I realised the key thing I was doing wrong was trying to circumvent model binding, so I created a class/type Rating that represents each row (each column as a property) and then an Assessment type/class that contains a List as one of the properties.
On the Razor page:
#foreach (Comp c in Model.GetComps())
{
count++;
Model.assessment.Ratings.Add(new Rating());
Model.assessment.Ratings[count].AchievedCompetencyID = c.AchievedCompetencyID;
Code behind:
public void OnPost()
{
using (IDbConnection con = new SqlConnection(Startup.conStr))
{
long assessID = con.Insert(assessment);
foreach (Rating r in assessment.Ratings)
{
r.AssessmentID = Convert.ToInt32(assessID);
con.Insert(r);
}
}
}

Saving user ID with Entity Framework

I'm using entity framework v6.2.0 and ASP Net MVC to create a web page to access a database and edit the entries. The overwhelming majority of the code is the basic framework provided for me. The database is connected successfully and entries can be viewed, edited, and deleted. Additionally I have implemented some rudimentary paging, searching, and sorting as instructions are provided by microsoft on how to implement those. The last thing I need to do before the site is truly functional is to pull the userID from the users login and save that as the EnteredBy field before saving any changes or new entries to the table.
if (ModelState.IsValid)
{
string currentUserId = User.Identity.GetUserId();
yasukosKitchen.EnteredBy = currentUserId;
db.YasukosKitchens.Add(yasukosKitchen);
db.SaveChanges();
return RedirectToAction("Index");
}
This code seems very simple, and I added using Microsoft.AspNet.Identity; so it compiles fine. However when I attempt to test this code the EnteredBy field is left blank or null.
My search for information turned up a post suggesting the use of the following line of code.
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
However when I attempt to add that I get an error, the ApplicationUser cannot be found and Users does not exist in this context. The fix for this is probably staring me in the face but my lack of experience and comprehension is killing me.
As suggested: My question is, how do I get and/or correctly add the UserId to my database entry?
If your Database Context has an entry to your YasukosKitchen table; usually something like this,
public virtual DbSet<YasukosKitchen> YasukosKitchens {get; set;}
and YasukosKitchen table has a column 'EnteredBy' (string 128 length), then you can post the value for the logged in user's Id straight from the View.
Add this to the very beginning of the Create view.
#using Microsoft.AspNet.Identity
#using Microsoft.AspNet.Identity.EntityFramework
At the end of the form just before the submit button, add this code.
#Html.HiddenFor(model => model.EnteredBy, new { #Value = User.Identity.GetUserId() })
I'm not sure what is the functionality of 'Users' table.

Related entities EF Count

Need help. I want count players from clubs and show how much players are playing in club. This is my View
But i want that my code show player count in club, like this
Here is my database structure :
My starting code
public int GetCountOfPlayersInClub(int clubId)
{
using (var db = new BasketDbContext())
{
return db.Player.Count(p => p.BasketBallClubId == clubId);
}
}
But what I do now, what I need write in my ActionResult Index()?
In order to display value in view, you need to pass it over model or viewbag.
In view you can call the passed variable via razor syntax (like #Viebag.CountAll).
Note that count is not very optimized in ef core and I would recommend to ran raw query for it.in testing I did , raw query is 100 times faster.

Show Columns Total Value in tfooter using html table

I am new in asp mvc and creating small application in mvc4. I have a problem I make index view which show list of all purchase contract which contain (cost, quantity,discount,tax) column.I want total value of all four column in tfooter how can I do this please help me.
Thanks for advance.
I assume your view is some thing like
#model List<Models.Purchase>
#{
var totalCost=Model.sum(a=>a.Cost);
var totalQty=Model.sum(a=>a.Qty);
var totalDiscount=Model.sum(a=>a.Discount);
var totalTax=Model.sum(a=>a.Tax);
}
<table>
<tr><th>Cost</th><th>Qty</th><th>Discount</th><th>Tax</th></tr>
#foreach(var item in Model)
{
<tr><td>#item.Cost</td><td>#item.Qty</td><td>#item.Discount</td><td>#item.Tax</td></tr>
}
<tr><th>#totalCost</th><th>#totalQty</th><th>#totalDiscount</th><th>#totalTax</th></tr>
</table>
Please try this. I hope you can understand.

How to create a new product from a custom form and then add it to the cart?

I am trying to develop a custom page on PS 1.6 where a customer could create a new product from a form and then add it to the cart.
Let's say for example, i am selling woodcrafts and i want my customers to fill a form where they need to specify the type of wood, dimensions, ...
Depending on these criterias, the price would be modified and it will create a "final" product that will be added to the customer's cart.
I know how i will develop the form and i believe i can add the product to the cart with updateQty() from Cart.php but how do i instanciate my product from the data i get from the form? I am trying to search through all files but i can't seem to find where new products are instanciated from.
Thanks in advance for the help
I'm answering my question since i managed to do it. Here's my solution :
public static function créerProduct($name, $ean13, $category, $price, $description, $reference){
$product = new Product();
$languages=Language::getLanguages();
foreach($languages as $lang){
$product->name[$lang['id_lang']]=$name;
$product->link_rewrite[$lang['id_lang']]=$name;
$product->description[$lang['id_lang']]=$description;
}
$product->reference=$reference;
$product->quantity=0;
$product->id_category_default=$category;
$product->id_category[]=$product->id_category_default;
$product->price=$price;
$product->id_tax_rules_group=1;
$product->indexed=0;
try{
$product->save();
} catch (PrestaShopException $e){
echo $e->displayMessage();
}
$product->updateCategories(array_map('intval', $product->id_category));
StockAvailable::setQuantity($product->id,'',1);
return $product->id;
}
public static function addProduitauPanier($id_product){
$context=Context::getContext();
$result=$context->cart->updateQty(1,$id_product);
}
Can you not use attributes to develop the product? The reason being is that you are going to have in effect customers adding information to your database and then you are going to have to sanitize it and validate it. I would use Prestashop's built in attributes for doing something like this.