Inserting list from view to Model in MVC c# - c#

I have been returning a list from my controller to the view;
public ActionResult Raffle_Conso(int conso = 0)
{
return View(db.Users_Info.Where(s=>s.by_name_rank == null).OrderBy(t => Guid.NewGuid()).Take(conso));
}
In my view, I looped it and put in an input field.
#using (Html.BeginForm("InsertRafflers","Events", FormMethod.Post))
{
#foreach (var item in Model)
{
<input type="text" name="rafflers_name" value="#item.rafflers_name" />
}
<input type="submit" value="Insert list" />}
}
It displayed the list. I like to ask if how would it be possible to insert the list from the view to the database via controller?
Any idea is really appreciated. Thanks.

Your control name needs to be named like an array...
#using (Html.BeginForm("InsertRafflers","Events", FormMethod.Post))
{
var textIndex = 0;
#foreach (var item in Model)
{
#<input type="text" name="rafflers_name[#textIndex]" value="#item.rafflers_name" />
textIndex += 1;
}
<input type="submit" value="Insert list" />}
}

Related

Passing data to Controller failing (Tuple being used)

I have a page which displays fields from 2 different models. To ensure this works I am using Tuple<> to display them both and have tested to ensure data shows which it does. The issue I had was when I submitted the form to update the database, nothing was passed and the record was wiped clean. Please advise me on how to proceed. I have shortened fields shown to make the post shorter.
View
#model Tuple<CommunityParkletDashboard.Models.COMMUNITY_PARKLET_APPLICATION, CommunityParkletDashboard.ViewModels.CPDashboardModel>
<input type="button" value="Back" onclick="location.href='#Url.Action("CPDashboard", "CPDashboard")'" />
#using (Html.BeginForm("EditCP", "CPDashboard", FormMethod.Post))
{
<p>
Reference Number:
#Html.DisplayFor(i => i.Item1.REF_NUMBER)
</p>
<p>
Name:
#Html.DisplayFor(i => i.Item1.NAME)
</p>
<p>
Notes:
#Html.TextAreaFor(i => i.Item1.NOTES)
</p>
foreach (var item in Model.Item2.lParkletApplicationDtos)
{
<p>
Title:
#Html.DisplayFor(i => item.ParkletTitle)
</p>
<br />
<input type="submit" value="Save" />
}
}
Controller
[HttpPost]
public ActionResult EditCP(COMMUNITY_PARKLET_APPLICATION cpa, int id)
{
_context.UpdateParkletApplication(cpa, id);
return RedirectToAction("CPDashboard");
}
UpdateParkletApplication() is just a method which runs some SQL script to update the data using the model and ID so associate the record with, all this was working fine before I introduced second model. Thanks in advance.
Because you create one form and use foreach form item2 it pass all item in item2.
You can use foreach and inside of it use begin form .
foreach (var item in Model.Item2.lParkletApplicationDtos)
{
#using (Html.BeginForm("EditCP", "CPDashboard", FormMethod.Post))
{
<p>
Reference Number:
#Html.DisplayFor(i => i.Item1.REF_NUMBER)
</p>
<p>
Name:
#Html.DisplayFor(i => i.Item1.NAME)
</p>
<p>
Notes:
#Html.TextAreaFor(i => i.Item1.NOTES)
</p>
<p>
Title:
#Html.DisplayFor(i => item.ParkletTitle)
</p>
<br />
<input type="submit" value="Save" />
}
}
Does it pass id ???
#Html.DisplayFor(i => item.ParkletTitle)
As your view contains model as
#model MyCustomModel
Following method should like this and then access cpa.Item1 just you did in view.
[HttpPost]
public ActionResult EditCP(MyCustomModel cpa, int id)
{
_context.UpdateParkletApplication(cpa, id);
return RedirectToAction("CPDashboard");
}
Your Model Class
public class MyCustomModel
{
public CommunityParkletDashboard.Models.COMMUNITY_PARKLET_APPLICATION Item1 {get;set;}
public CommunityParkletDashboard.ViewModels.CPDashboardModel Item2 {get;set;}
}
Ultimately you have to think like how is model constructed. Even if in View you keep Tuple then you can use above answer.

attribute information not being found

When the button is pressed it states that the model is invalid as fields are empty.
when looking at the model all fields are empty or null. anyone know how to solve this issue, thanks
Home Controller
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> createOrderLine(Product models)
{
if (ModelState.IsValid)
{
db.OrderLines.Add(new OrderLine
{
productId = models.productId,
productColour = models.productColour,
productDescription = models.productDescription,
productName = models.productName,
productPrice = models.productPrice,
productStock = models.productStock,
//QuantityOrdered = quantityOrdered
});
db.SaveChanges();
return RedirectToAction("Index", "OrderLines");
}
else return RedirectToAction("Index", "Home");
}
Home Index - Displays the product information to the screen
#foreach (var product in Model)
{
using (Html.BeginForm("createOrderLine", "Home", FormMethod.Post, new {
#class = "form-horizontal", role = "form" }))
{
<div class="row">
<div class="blog col-md-6">
<div>
<h1>Product Name</h1>
<h2>#product.productName</h2>
<div>
<h3>Product Description</h3>
<h6><i>#product.productDescription</i></h6>
<br />
<h3>Product Price</h3>
<td>#product.productPrice </td>
<br />
<h1>Product colour</h1>
<td>#product.productColour</td>
<div></div>
<br />
<br />
#Html.AntiForgeryToken()
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-buy" value="Add to cart" onclick="btnbuy_Click" />
</div>
</div>
</div>
</div>
<br />
</div>
</div>
}
}
the problem is that none of your field are linked to the model they only display it so to fix this
you can simply add a hiddenfor field that links the product id in your page like so for each of your product :
#Html.HiddenFor(product.Id)
then fill the rest of the informations you need with the id that is gonna be passed to your controller as a parameter
exemple :
public ActionResult createorderline(Product ProductToAdd)
{
// add your product or do your treatment
}
I do not quite understand what are you trying to do, but Louis is right. If you are trying to pass values back, you have to #Html.EditorFor() or some other ways to pass back information to the server.
You could also use #Html.HiddenFor(product.Id) then inside your Actionmethod call the database to get the rest of the info regarding your product or you could use JQuery as well.
In this case I would only use the #Html.HiddenFor(product.Id) and have a static helper method that will map your orderline class from the DB.
public static Product GetProductById(int productId){
return db.Products.FirstOrDefault(x => x.Id == productId);
}
But again you could just add the FirstOrDefault() line inside your controller as you not mapping from a ViewModel to a business Model.

asp.net mvc Getting values from Html.Checkbox

I want to be able to select a few boxes and send the strings correlating to them. The problem however is that I don't know how to catch the values in the controller.
One important issue is that I do not want to bind it to a model! Hopefully you can help me find a solution that fits in this image
cshtml file:
#model IEnumerable<WebApplication1.Models.WikiPage>
#using (Html.BeginForm("DeletePages", "Home", FormMethod.Post))
{
<ul>
#foreach (var item in #Model)
{
<li>
#Html.CheckBox(item.Title)
#Html.Label(item.Title)
</li>
}
</ul>
<input type="submit" value="Delete pages" />
}
And here is the part in the controller. String... will be null and I don't know what I should put in there to catch the values
[HttpPost]
public ActionResult DeletePages(String... Titles)
{
removePages(Titles);
List<WikiPage> pages = db.WikiPages.ToList();
return View(pages);
}
Hope you can help me!
Kind regards
View:
#model IEnumerable<WebApplication1.Models.WikiPage>
#using (Html.BeginForm("DeletePages", "Home", FormMethod.Post))
{
<ul>
#foreach (var item in Model)
{
<li>
<label>#item.Title
<input type="checkbox" name="titles" value="#item.Title />
</label>
</li>
}
</ul>
<input type="submit" value="Delete pages" />
}
Controller:
[HttpPost]
public ActionResult DeletePages(string[] titles)
{
removePages(titles);
List<WikiPage> pages = db.WikiPages.ToList();
return View(pages);
}

How to sort a list of users roles in MVC?

What is the best way to sort a SelectList of users roles like below? I want the role names to appear in alphabetical order.
This my controller code:
ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
This is my view code:
#foreach (var item in (SelectList)ViewBag.RoleId)
{
input type="checkbox" name="SelectedRoles" value="#item.Value" class="checkbox-inline" />
}
UPDATE - WORKING CODE:
Controller:
var getRoles = await RoleManager.Roles.ToListAsync();
ViewBag.Roles = getRoles.OrderBy(x => x.Name);
View:
#foreach (var item in ViewBag.Roles)
{
<input type="checkbox" name="SelectedRoles" value="#item.Name" class="checkbox-inline" />
<label for="#item.Name" class="control-label">#item.Name</label>
}
Amend your controller code to
ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name").OrderBy(x => x.Text);
If you do this you will then need to change the cast in your view to:
#foreach (var item in (IEnumerable<SelectListItem>)ViewBag.RoleId)
It may be easier to simply change your view code to:
#foreach (var item in ((SelectList)ViewBag.RoleId).OrderBy(x => x.Text))
{
input type="checkbox" name="SelectedRoles" value="#item.Value" class="checkbox-inline" />
}
as this means no changes to the controller code.

ASP.NET MVC Redirect

I work on one of my first ASP MVC-programs at the moment.
The program should show me a list of product, and with a link beneath the name of the product it should be possible to edit the product. No problem so far.
#model MVC3Demo.Product
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm("Save", "Product"))
{
<div>
<input type="hidden" id="ID" name="ID" value="#Model.ID" />
ProduktID #Model.ID
</div>
<div>
Produktname <input id="Name" name="Name" type="text" value=#Model.Name />
</div>
<div>
Preis <input id="Price" name="Price" type="text" value=#Model.Price />
</div>
<div>
<input type="submit" value="Speichern"/>
</div>
}
Now I have written a Save action method that should update my data:
public ActionResult Save(Product p)
{
ProductRepository rep = new ProductRepository();
rep.Update(p);
return RedirectToAction("List");
}
The "List"-View is where I can see all products with the edit-link.
The problem is, that if I press the save-button, it redirects me to the old list, not to the updated one. I debugged my project and I´m sure that the update-method works correct and updates the product.
My List action is:
#model IEnumerable<MVC3Demo.Product>
#{
ViewBag.Title = "List";
}
<h2>List</h2>
<ul>
#foreach (MVC3Demo.Product p in Model)
{
<li>#p.Name #Html.ActionLink("bearbeiten", "Edit", "Product", p, null)</li> //new{ ID = p.id}
}
</ul>
Because you asked, here is the List Action:
public ActionResult List()
{
ProductRepository rep = new ProductRepository();
return View(rep.GetAll());
}
So where could be my mistake?
It looks like you're calling the update, but you're not actually submitting the transaction itself, does your repository have a SubmitChanges, AcceptChanges or Commit or something similar? As with DataTables, your changes won't actually take effect (save to the database) until you call AcceptChanges.
Try include an HttpPost attribute at Save controller method.
[HttpPost]
public ActionResult Save(Product p)
{
ProductRepository rep = new ProductRepository();
rep.Update(p);
return RedirectToAction("List");
}

Categories

Resources