My question is how to get table data back to the controller from view?
I have class in my model:
public class Company
{
public string Name { get; set; }
public int ID { get; set; }
public string Address { get; set; }
public string Town { get; set; }
}
and I pass list of Companies to my view as:
#model IEnumerable<MyTestApp.Web.Models.Company>
....
#using (Html.BeginForm("Edit", "Shop"))
{
<table id="example">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.DisplayNameFor(model => model.Town)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.EditorFor(modelItem => item.Name)
</td>
<td>
#Html.EditorFor(modelItem => item.Address)
</td>
<td>
#Html.EditorFor(modelItem => item.Town)
</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Submit" />
}
And everything looks ok, but I can't understand how to get modified data in the controller? I used these approaches:
public ActionResult Edit(IEnumerable<Company> companies)
{
// but companies is null
// and ViewData.Model also is null
return RedirectToAction("SampleList");
}
I need access to modified objects, what am I doing wrong?
UPDATE: Thanks to webdeveloper, I just needed use 'for' loop instead of 'foreach' loop. Right version is
<tbody>
#for (int i = 0; i < Model.Count(); i++ ) {
<tr>
<td>
#Html.EditorFor(modelItem => modelItem[i].Name)
</td>
<td>
#Html.EditorFor(modelItem => modelItem[i].Address)
</td>
<td>
#Html.EditorFor(modelItem => modelItem[i].Town)
</td>
</tr>
}
</tbody>
Please, look at my answer here: Updating multiple items within same view OR for Darin Dimitrov answer.
You need items with index in name attribute in rendered html markup. Also you could look at: Model Binding To A List
I think that you are missing the Company's ID in your form so that the model can be correctly bound.
You should add it like this:
#using (Html.BeginForm("Edit", "Shop"))
{
<table id="example">
<thead>
<tr>
<th>
#Html.HiddenFor(model => model.ID)
#Html.DisplayNameFor(model => model.Name)
</th>
...
Otherwise the rest of your code seems to be OK.
You need to bind your table rows by providing an id for each one being edited so mvc can bind to it back to the controller. One row of table data example:
#for (var a = 0; a < #Model.Pets.Count; a++)
{
<tr>
<td>
#Html.CheckBoxFor(model => #Model.Pets[a].ChildSelected, new { #id= a + "childSelected" })
</td>
</tr>
Related
I'm inserting data from one (model)table to another, but it is passing null values.
Here is the code for the controller :
public ActionResult PendingBlogs()
{
OMSDataContext db = new OMSDataContext();
var query = from a in db.BlogApprovals
select a;
return View(query);
}
[HttpPost]
public ActionResult PendingBlogs(BlogApproval blogap)
{
OMSDataContext db = new OMSDataContext();
Blog b = new Blog
{
BlogTitle = blogap.BlogTitle1,
BlogContent = blogap.BlogContent1,
UserName = blogap.UserName1,
Date = blogap.Date1,
IsApproved = true
};
db.Blogs.InsertOnSubmit(b);
db.SubmitChanges();
return RedirectToAction("Index");
}
And here is my View code :
#model IEnumerable<MVCDemo.Models.BlogApproval>
#{
ViewBag.Title = "PendingBlogs";
}
<h2>PendingBlogs</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.BlogTitle1)
</th>
<th>
#Html.DisplayNameFor(model => model.BlogContent1)
</th>
<th>
#Html.DisplayNameFor(model => model.UserName1)
</th>
<th>
#Html.DisplayNameFor(model => model.Date1)
</th>
<th>
#Html.DisplayNameFor(model => model.IsApproved1)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.BlogTitle1)
</td>
<td>
#Html.DisplayFor(modelItem => item.BlogContent1)
</td>
<td>
#Html.DisplayFor(modelItem => item.UserName1)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date1)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsApproved1)
</td>
<td>
<form asp-controller="Admin" method="post">
<input type="submit" name="answer" value="RunRegisterdJob" />
</form>
</td>
</tr>
}
</table>
The two models (Blog and BlogApproval) are tables in the models folder. BlogApproval has data inside it, but it's not returning the data from the table for some reason.
I've looked at this thread, and have renamed the columns in the BlogApproval table so that they are different from the columns on the Blog table, but that didn't fix it.
Your form tag does not contain any html input value ,so instead of using below code
<form asp-controller="Admin" method="post">
<input type="submit" name="answer" value="RunRegisterdJob" />
</form>
use below code:
<form asp-controller="Admin" method="post">
<input type="text" name="blogTitle1"/>
<input type="text" name="blogContent"/>
<input type="text" name="UserName1"/>
<input type="submit" name="answer" value="RunRegisterdJob" />
</form>
I have the following problem:
Business Problem: I have over 500 ETF's around the world categorized into different types (Region of the world, Capital type (small cap/large cap) etc which are different fields in a SQL database.
Coding Problem: I am able to show the entire list of ETF's, sort them etc. The problem lies in creating 5 different tables (5 regions of the world) on the same web page. In the SQL World it would be a simple
Select * from ETF where RegionDS = 'Europe'
Where I am Today: I am able to query the database and retrieve all the ETF's and show them successfully on the page, but am not able to filter them in any way. Here is the M/V/C for just one table. Hopefully someone can piece it together for me.
MODEL
namespace SmartAdminMvc.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public partial class ETF
{
[Key]
public string Symbol { get; set; }
[Key]
public System.DateTime TodaysDate { get; set; }
public string SubSectorDS { get; set; }
public Nullable<int> RANK { get; set; }
public string RegionDS { get; set; }
VIEW
#model IEnumerable<SmartAdminMvc.Models.ETF>
<table id="dt_basic" class="table table-striped table-bordered table-hover" width="100%">
<thead>
<tr>
<th> #Html.DisplayNameFor(model => model.RANK)</th>
<th> <a title=#Html.DisplayNameFor(model => model.Symbol)> #Html.DisplayNameFor(model => model.Symbol) </a> </th>
<th> <a title=#Html.DisplayNameFor(model => model.TodaysDate)>#Html.DisplayNameFor(model => model.TodaysDate) </a> </th>
<th> <a title=#Html.DisplayNameFor(model => model.SectorDS)>#Html.DisplayNameFor(model => model.SectorDS) </a> </th>
<th> <a title=#Html.DisplayNameFor(model => model.RegionDS)>#Html.DisplayNameFor(model => model.RegionDS) </a> </th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.OrderBy(item => item.RANK).Take(50))
{
if (item.RegionDS == "Europe")
{
<tr>
<td align="right"> #Html.DisplayFor(modelItem => item.RANK) </td>
<td align="right"> #Html.DisplayFor(modelItem => item.Symbol) </td>
<td align="right"> #Html.DisplayFor(modelItem => item.TodaysDate) </td>
<td align="center"> #Html.DisplayFor(modelItem => item.SectorDS) </td>
<td align="center"> #Html.DisplayFor(modelItem => item.RegionDS) </td>
</tr>
}
}
</tbody>
</table>
CONTROLLER:
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using SmartAdminMvc.Models;
namespace SmartAdminMvc.Controllers
{
public class ETFsController : Controller
{
private QlikEntities db = new QlikEntities();
// GET: vDailyPickSummaryTotals
public ActionResult ETFWorld()
{
return View(db.ETFs.ToList());
}
Currently you're taking the top 50 from the whole list, and then trying to filter out by region. But, this will only return the matches in those 50 records, if any. Instead, do the filter first:
<tbody>
#foreach (var item in Model.Where(w => w.RegionDS == "Europe").OrderBy(item => item.RANK).Take(50))
{
<tr>
<td align="right"> #Html.DisplayFor(modelItem => item.RANK) </td>
<td align="right"> #Html.DisplayFor(modelItem => item.Symbol) </td>
<td align="right"> #Html.DisplayFor(modelItem => item.TodaysDate) </td>
<td align="center"> #Html.DisplayFor(modelItem => item.SectorDS) </td>
<td align="center"> #Html.DisplayFor(modelItem => item.RegionDS) </td>
</tr>
}
</tbody>
EDIT:
If you're only displaying a subset of the records you could create a ViewModel such as this:
public class MyViewModel
{
public IEnumerable<ETF> EuropeETFs {get; set;}
public IEnumerable<ETF> AsiaETFs {get; set;}
...
}
Then in your controller:
MyViewModel vm = new MyViewModel();
vm.EuropeETFs = db.ETFs.Where(w => w.RegionDS == "Europe").OrderBy(item => item.RANK).Take(10);
....
Change the model type of your View to MyViewModel, then:
<tbody>
#foreach (var item in Model.EuropeETFs)
{
<tr>
<td align="right"> #Html.DisplayFor(modelItem => item.RANK) </td>
<td align="right"> #Html.DisplayFor(modelItem => item.Symbol) </td>
<td align="right"> #Html.DisplayFor(modelItem => item.TodaysDate) </td>
<td align="center"> #Html.DisplayFor(modelItem => item.SectorDS) </td>
<td align="center"> #Html.DisplayFor(modelItem => item.RegionDS) </td>
</tr>
}
</tbody>
I have a Form which is filled with some grid like structure with CheckBoxes and DisplayField.
I want to fetch rows with Checked CheckBoxes. Problem is i am getting null in Controller's post method.
Models
public class RegisterModuleSelection
{
[Display(Name = "ID")]
public int mID { get; set; }
[Display(Name = "Module")]
public string Module { get; set; }
[Display(Name = "Buy")]
public bool Buy { get; set; }
}
View
#model IEnumerable<MAK_ERP.Models.RegisterModuleSelection>
#{
ViewBag.Title = "Register - Modules Selection";}
<h2>
Register - Modules Selection</h2>
#using (Html.BeginForm("RegisterModules", "UserAccount", FormMethod.Post, new { id = "RegisterModules", #class = "generalForm" }))
{
<table class="Grid Module">
<tr>
<th>
#Html.DisplayNameFor(model => model.Module)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th>
#Html.DisplayNameFor(model => model.Duration) (Months)
</th>
<th>
#Html.DisplayNameFor(model => model.Buy)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.HiddenFor(modelItem => item.mID)
#Html.DisplayFor(modelItem => item.Module)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.EditorFor(modelItem => item.Duration)
</td>
<td>
#Html.CheckBoxFor(modelItem => item.Buy)
</td>
</tr>
}
<tr>
<td colspan="4">
<input type="submit" value="Next" class="button3" />
<input type="reset" value="Reset" class="button4" />
</td>
</tr>
</table>
}
Controller
[HttpGet]
public ActionResult RegisterModules()
{
IEnumerable<MAK_ERP.Models.RegisterModuleSelection> model = reg.getModules();
return View(model);
}
[HttpPost]
public ActionResult RegisterModules(IEnumerable<Models.RegisterModuleSelection> regMod)
{
//regMod is null here
...
Unfortunately you cannot bind in this way. Model binding depends upon how generated html looks like. In this particular case it should look something like:
<input id="item_Buy" type="checkbox" value="true" name="item[0].Buy" checked="checked">
If you are okay with some workarounds, you can use a for loop instead of foreach loop where you can add an index to each control name and model binder could bind them properly.
There are some really helpful discussions available, you can check here: ASP.NET MVC - Insert or Update view with IEnumerable model. And also Model Binding To A List. Another one is: Modelbinding IEnumerable in ASP.NET MVC POST?
You should use EditorTemplates to solve the problem.
The accepted answer at ASP.NET MVC Multiple Checkboxes would help you.
i'm using Razor with MVC3 in my project. I use membership to handle user registration and i want to diplay all my users into a table .
here's my Action:
public ActionResult ListProfile()
{
//ProfileInfoCollection profiles = ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All);
//return View(profiles);
var users = Membership.GetAllUsers();
return View(users);
}
My View :
#inherits System.Web.Mvc.ViewPage<MembershipUserCollection>
#{
ViewBag.Title = "Documents";
}
<h2>Liste des documents</h2>
<table style="width: 100%;">
<tr>
<th>Nom
</th>
</tr>
#foreach (MembershipUser item in Model)
{
<tr>
<td>
<h4>
#item.UserName
</h4>
</td>
</tr>
}
</table>
But i get an error : CS0115: 'ASP._Page_Views_AccountProfile_listProfile_cshtml.Execute()': no suitable method found to override
Have to change the basetype to System.Web.Mvc.WebViewPageinstead of System.Web.Mvc.ViewPage because razor configuration is under ~/Views/Web.config
Here is the view :
#inherits System.Web.Mvc.WebViewPage<MembershipUserCollection>
#{
ViewBag.Title = "Documents";
}
<h2>Liste des documents</h2>
<table style="width: 100%;">
<tr>
<th>Nom
</th>
</tr>
#foreach (MembershipUser item in Model)
{
<tr>
<td>
<h4>
#item.UserName
</h4>
</td>
</tr>
}
</table>
i have following View where user has a table of products and i need select all data where "Quantity > 0" default is 0. But i dont know how can i get collection of data from table. Thanks for respond.
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Produkty</legend>
<table>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(model => item.Product.Name)
</td>
<td>
#Html.DisplayFor(model => item.Product.Price)
</td>
<td>
#Html.EditorFor(model => item.Quantity)
</td>
</tr>
}
<p>
<input type="submit" value="Orders" />
</p>
</table>
</fieldset>
}
//Controller
public ActionResult Index()
{
List<ProductListViewModel> productList = new List<ProductListViewModel>();
foreach (var item in db.Products.ToList())
{
ProductListViewModel model = new ProductListViewModel();
model.Product = item;
model.Quantity = 0;
productList.Add(model);
}
return View(productList);
}
Since you're using Html.EditorFor, things are easy.
Put productList as parameter in your Index Action(for Post), MVC will auto combine form data to productList Object, so you just need to filter the quantity in server side with a loop.
Of cause, to identify the product object, you'd better also add a hidden ID in your view.
<table>
#for(int i = 0; i<Model.Count; i++) {
<tr>
<td>
#Html.HiddenFor(model => Model[i].Product.ID)
#Html.DisplayFor(model => Model[i].Product.Name)
</td>
<td>
#Html.EditorFor(model => Model[i].Quantity)
</td>
</tr>
}
[HttpPost]
public ActionResult Index(List<ProductListViewModel> productList)
{
\\...
}