This question already has answers here:
Post an HTML Table to ADO.NET DataTable
(2 answers)
Closed 5 years ago.
I am trying to call Action method "Createdirect" on form submission from Index.cshtml view.
I want to list and create in the same view. Code works for list..it displays data, but when trying to create, it does not pass form data to action method.. It passes null values as shown in screenshot attached..
Index.cshtml
#using CRUD_Entity_DataFirst.Models
#model Tuple<Customer_MVC,IEnumerable<Customer_MVC>>
#{
ViewBag.Title = "Index";
}
<h4>Customers</h4>
<link href="#Url.Content("~/Content/table.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>
<script src="#Url.Content("~/Scripts/select.js")"></script>
<script src="#Url.Content("~/Scripts/table.js")"></script>
#Html.DropDownList("searchby", new SelectList(Enum.GetValues(typeof(search))), "- - Search By - -")
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search ..">
<label id="bdy" style="color:red"></label>
<table class="table" id="myTable">
<tr>
<th>
#Html.DisplayNameFor(model => model.Item1.First_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.Last_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.Email)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.Mobile)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.Address_Temp)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.Address_Perm)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.State)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.City)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.Zipcode)
</th>
<th></th>
</tr>
#foreach (var item in Model.Item2)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.First_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Last_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.Mobile)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address_Temp)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address_Perm)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.Zipcode)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("View", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { onclick = "return confirm('Are you sure wants to delete?');" })
</td>
</tr>
}
</table>
#using (Html.BeginForm("Createdirect","Customer",FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.EditorFor(model => model.Item1.First_Name, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.First_Name, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Item1.Last_Name, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.Last_Name, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Item1.Email, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.Email, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Item1.Mobile, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.Mobile, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Item1.Address_Temp, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.Address_Temp, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Item1.Address_Perm, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.Address_Perm, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.Item1.State, new SelectList(Enum.GetValues(typeof(States))), "State", new { #class = "form-control", #style = "width:80px" })
#Html.ValidationMessageFor(model => model.Item1.State, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.Item1.City, new SelectList(Enum.GetValues(typeof(Cities))), "City", new { #class = "form-control", #style = "width:80px" })
#Html.ValidationMessageFor(model => model.Item1.City, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Item1.Zipcode, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.Zipcode, "", new { #class = "text-danger" })
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
CustomerController.cs
// GET: Customer
public ActionResult Index()
{
if (Session["User"] == null)
{
return RedirectToAction("Login");
}
return View(Tuple.Create<Customer_MVC,IEnumerable<Customer_MVC>>(new Customer_MVC(),vd.Customer_MVC.ToList()));
}
//create:post
[HttpPost]
public ActionResult Createdirect(Customer_MVC custcreate)
{
if (ModelState.IsValid)
{
vd.Customer_MVC.Add(custcreate);
vd.SaveChanges();
return RedirectToAction("Index");
}
return View(custcreate);
}
Customer_MVC.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CRUD_Entity_DataFirst.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(CustomersValid))]
public partial class Customer_MVC
{
public int Id { get; set; }
public string First_Name { get; set; }
public string Last_Name { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Address_Temp { get; set; }
public string Address_Perm { get; set; }
public string City { get; set; }
public string State { get; set; }
public Nullable<int> Zipcode { get; set; }
}
}
here it showing null values
Model binding does not work when you use a foreach loop as the html controls are not rendered with meaningful IDs.
Change your loop to a for loop:
#for (int i = 0; i < Model.Item2.Length; i++)
{
<tr>
<td>
#Html.DisplayFor(model => model.Item2[i].First_Name)
</td>
<td>
...
You may also have an issue (but try it first) as the IEnumerable is not an instance at the point of binding. If this is the case then the only solution would be to change your Tuple based model to a class implementation:
public class MyModel
{
public Customer_MVC Item1 { get; set; }
public IEnumerable<Customer_MVC> Item2 { get; set; } = new List<Customer_MVC>();
}
Related
I'm new to .net. I have this model that has been a real trouble for me for days.
class DetailedRecordModel
public class DetailedRecordModel
{
public string RecordID { get; set; }
public string EmployeeID { get; set; }
public string CustomerID { get; set; }
[DataType(DataType.Date)]
public string InitDate { get; set; }
[DataType(DataType.Date)]
public string DeliveryDate { get; set; }
public virtual ICollection<PurchaseDetail> detail{ get; set; }
}
class PurchaseDetail
public class PurchaseDetail
{
public string ProductID { get; set; }
public int Qty { get; set; }
public double price { get; set; }
public string RecordID { get; set; }
}
controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(DetailedRecordModel record)
{
if (ModelState.IsValid)
{
return View(record);
}
return RedirectToAction("ViewRecords");
}
html
<div class="form-group">
#Html.LabelFor(model => model.EmployeeID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.EmployeeID, (IEnumerable<SelectListItem>)ViewData["sellistemp"])
#Html.ValidationMessageFor(model => model.EmployeeID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CustomerID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CustomerID, (IEnumerable<SelectListItem>)ViewData["sellistcust"])
#Html.ValidationMessageFor(model => model.CustomerID, "", new { #class = "text-danger" })
</div>
</div>
<tr>
<td style="display:none" id="Index0" name="detail.Index" value="0"></td>
<td>1</td>
<td id="ProductID" name="detail[0].ProductID" value="sp00002">sp00002</td>
<td id="Qty" name="detail[0].Qty" value="12123">12123</td>
<td id="price" name="detail[0].price" value="2312">2312</td>
</tr>
<tr>
<td style="display:none" id="Index1" name="detail.Index" value="1"></td>
<td>2</td>
<td id="ProductID" name="detail[1].ProductID" value="sp00003">sp00003</td>
<td id="Qty" name="detail[1].Qty" value="2323">2323</td>
<td id="price" name="detail[1].price" value="3223">3223</td>
</tr>
for RecordID, EmployeeID, CustomerID, InitDate and DeliveryDate passing them to the controller is all fine, however I always get null for <PurchaseDetail> detail. How can I solve this problem?
you have to pass the model to the view by using View(myModel) or RedirectToAction("ViewRecords", record)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(DetailedRecordModel record)
{
if (ModelState.IsValid)
{
return RedirectToAction("ViewRecords", record);
}
return View(record);
}
public IActionResult ViewRecords(DetailedRecordModel model)
{
return View(model);
}
then in the View you can access the model like here How to pass model in MVC view
add the definition of your model at the top of #model DetailedRecordModel;
after you added the model you can access it everywhere in your file with #Model (in html) or Model
#model DetailedRecordModel;
#{
ViewData["Title"] = "ViewRecords";
}
<h1>ViewRecords</h1>
<div class="form-group">
#Html.LabelFor(model => model.EmployeeID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.EmployeeID, (IEnumerable<SelectListItem>)ViewData["sellistemp"])
#Html.ValidationMessageFor(model => model.EmployeeID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CustomerID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CustomerID, (IEnumerable<SelectListItem>)ViewData["sellistcust"])
#Html.ValidationMessageFor(model => model.CustomerID, "", new { #class = "text-danger" })
</div>
</div>
#foreach (var entry in Model.detail)
{
<tr>
<td style="display:none" id="Index0" name="detail.Index" value="0"></td>
<td>1</td>
<td id="ProductID" name="#entry.ProductID" value="sp00002">sp00002</td>
<td id="Qty" name="#entry.Qty" value="12123">12123</td>
<td id="price" name="#entry.price" value="2312">2312</td>
</tr>
}
After 2 wretching days of desperation I know that in order to bind the values, I found the answer by declaring an object DetailedRecordModel inside model PurchaseDetail and I have to change the name of each <input> tag into detail[index].somevariable
I m implement a drop-down list with entity framework database first approach in asp.net MVC??
I implement a drop-down list in MVC and when I M debugging In watch Window My Inserted Record Is display but Not Inserted In Database that is an issue??
DatabaseField Name:
tbl_product
ProductID int
ProductName varchar(50)
ProductList varchar(50)
tbl_product.cs
// <auto-generated>
// </auto-generated>
public partial class tbl_product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string ProductList { get; set; }
public IEnumerable<SelectListItem> ProductLists { get; set; }
}
HomeController.cs
ProductEntities prodb = new ProductEntities();
public ActionResult Index()
{
return View(prodb.tbl_product.ToList());
}
public ActionResult Prodlist()
{
var ProductLists = GetallProductList();
var model = new tbl_product();
model.ProductLists = GetSelectListItems(ProductLists);
return View(model);
}
[HttpPost]
public ActionResult Prodlist(tbl_product product)
{
var ProductLists = GetallProductList();
product.ProductLists = GetSelectListItems(ProductLists);
if (ModelState.IsValid)
{
prodb.tbl_product.Add(product);
return RedirectToAction("Index");
}
return View("Prodlist", product);
}
private IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)
{
var selectList = new List<SelectListItem>();
foreach (var element in elements)
{
selectList.Add(new SelectListItem
{
Value = element,
Text = element
});
}
return selectList;
}
private IEnumerable<string> GetallProductList()
{
return new List<string>
{
"FRIDGE",
"WASHING MACHINE",
"A.C",
};
}
}
view:
Prodlist.cshtml
<div class="form-group">
#Html.LabelFor(model => model.ProductName, htmlAttributes: new { #class = "control-label col-md-2" })
<div>
#Html.EditorFor(model => model.ProductName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductName, "", new { #class = "text-danger" })
</div>
</div>
//product list
<div class="form-group">
#Html.LabelFor(model => model.ProductList, htmlAttributes: new { #class = "control-label col-md-2" })
<div>
#Html.DropDownListFor(model => model.ProductList,Model.ProductLists,"Please Select Your Products:", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductList, "", new { #class = "text-danger" })
</div>
</div>
Model1.Context.cs
// <auto-generated>
// </auto-generated>
public partial class ProductEntities : DbContext
{
public ProductEntities()
: base("name=ProductEntities")
{
}
public virtual DbSet<tbl_product> tbl_product { get; set; }
}
Index.cshtml
#model IEnumerable<DropdownInsertMvc.Models.tbl_product>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.ProductName)
</th>
<th>
#Html.DisplayNameFor(model => model.ProductList)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ProductName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ProductList)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ProductID }) |
#Html.ActionLink("Details", "Details", new { id=item.ProductID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ProductID })
</td>
</tr>
}
</table>
When I m Debugging In Watch Window:
ProductList "FRIDGE" string
ProductLists Count = 3 System.Collections.Generic.IEnumerable {System.Collections.Generic.List}
ProductName "Electronics" string
record is not inserted in the database??
You missed prodb.SaveChanges() after prodb.tbl_product.Add(product); in Prodlist method.
for more information about SaveChanges() you can follow this link
I created a Model, View, and Controller. In my view, I loop through the collection of , and I create a table with each listed, along with a Save button.
When I click the Save button, the only data returned to the controller are the ID and LandownerID -- all the other fields show as null.
I have spent most of today searching google, and trying multiple answers, none of which worked.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,ExemptionNumber,IssueDate,KillCount,TRAPPING,SHOOTING,DOGS,OTHER,NO_INDICATION,NOTES,SPECIES,E_LANDOWNER,EXEM_YEAR,MethodOfDisposal,NO_DATA")] ExempKillData exempKillData)
{
if (ModelState.IsValid)
{
db.Entry(exempKillData).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index","Owners");
}
return View(exempKillData);
}
View:
#model IEnumerable<Exemptions.Models.ExempKillData>
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<table border="1" id="tbl">
<tbody>
..table headers snipped...
#foreach (var kill in Model)
{
<tr>
<td>
#Html.EditorFor(model => Model.First().ID, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</td>
<td>
#Html.EditorFor(model => Model.First().ExemptionNumber, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</td>
<td valign="top">
#Html.EditorFor(model => kill.IssueDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => kill.IssueDate, "", new { #class = "text-danger" })
</td>
<td valign="top">
#Html.EditorFor(model => kill.KillCount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => kill.KillCount, "", new { #class = "text-danger" })
</td>
<td valign="top">
#Html.EditorFor(model => kill.TRAPPING, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => kill.TRAPPING, "", new { #class = "text-danger" })
</td>
<td valign="top">
#Html.EditorFor(model => kill.SHOOTING, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => kill.SHOOTING, "", new { #class = "text-danger" })
</td>
<td valign="top">
#Html.EditorFor(model => kill.DOGS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => kill.DOGS, "", new { #class = "text-danger" })
</td>
<td valign="top">
#Html.EditorFor(model => kill.OTHER, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => kill.OTHER, "", new { #class = "text-danger" })
</td>
<td valign="top">
#Html.EditorFor(model => kill.NO_INDICATION, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => kill.NO_INDICATION, "", new { #class = "text-danger" })
</td>
<td valign="top">
#Html.EditorFor(model => kill.NOTES, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => kill.NOTES, "", new { #class = "text-danger" })
</td>
<td valign="top">
#Html.EditorFor(model => kill.SPECIES, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => kill.SPECIES, "", new { #class = "text-danger" })
</td>
<td valign="top">
#Html.EditorFor(model => kill.E_LANDOWNER, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => kill.E_LANDOWNER, "", new { #class = "text-danger" })
</td>
<td valign="top">
#Html.EditorFor(model => kill.EXEM_YEAR, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => kill.EXEM_YEAR, "", new { #class = "text-danger" })
</td>
<td valign="top">
#Html.EditorFor(model => kill.NO_DATA, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => kill.NO_DATA, "", new { #class = "text-danger" })
</td>
<td valign="top" align="center">
<input type="submit" value="Save" class="btn btn-default" />
</td>
</tr>
}
</tbody>
</table>
}
Model:
[Table("WHE.ExempKillData")]
public partial class ExempKillData
{
[Display(Name ="Exemption Number")]
public int? ExemptionNumber { get; set; }
[Display(Name = "Issue Date")]
[Column(TypeName = "datetime2")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? IssueDate { get; set; }
[Display(Name = "Kill Count")]
public int? KillCount { get; set; }
public int? TRAPPING { get; set; }
[Column(TypeName = "numeric")]
public int? SHOOTING { get; set; }
public int? DOGS { get; set; }
[Column(TypeName = "numeric")]
public int? OTHER { get; set; }
[Display(Name ="No Indication")]
public int? NO_INDICATION { get; set; }
[StringLength(200)]
public string NOTES { get; set; }
[StringLength(32)]
public string SPECIES { get; set; }
[Display(Name ="Landowner")]
public double? E_LANDOWNER { get; set; }
[Display(Name ="Exemption Year")]
[StringLength(4)]
public string EXEM_YEAR { get; set; }
[Display(Name ="No Data")]
[StringLength(40)]
public string NO_DATA { get; set; }
public string MethodOfDisposal { get; set; }
public int ID { get; set; }
}
}
I would expect that clicking Save would return the contents of that row back to the Controller Action, where the data could then be properly saved.
ModelState.IsValid is true for every record I try to edit, but as mentioned above, all fields except ID and E_Landowner are null.
Have you looked at the 'Network' tab in the inspector when you make a request? The parameters looks like below:
you can make a test on your environment right now. Inspect the element that is not binding correctly, and remove 'kill.' from its name:
When you press save, this single property should be bound correctly
The thing is, when you make 'EditorFor(model => kill.IssueDate), then the bolded text will be the parameter name when you make a request. So, if your model had a property of type ExempKillData, and named as 'kill', then the binding would work.
But no worries, I know what you want to do.
Just change the line
#Html.EditorFor(model => kill.IssueDate, new { htmlAttributes = new { #class = "form-control" } })
to
#Html.EditorFor(model => kill.IssueDate, null, "IssueDate", new { htmlAttributes = new { #class = "form-control" } });
the second parameter is a template which is not the one we're interested in that example, but the third one tells ASP.NET to set a different field name for that property.
I am rather dull when it comes to explaining, but I hope you got the idea :)
btw. You can remove all this 'Bind' text from method parameter. Only type and name of parameter is required
I am creating a form in a for loop in Razor.
#model SignAPI.ViewModels.ChannelManagerViewModel
#{
ViewBag.Title = "Index";
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#using (Html.BeginForm("Index", "ChannelManager", FormMethod.Post))
{
<div class="form-group">
#Html.LabelFor(m => m.CustomerNames, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.CustomerNameSelected, Model.CustomerNames, "Select", new { onchange = "this.form.submit();", #class = "form-control form-control-sm", #id = "CustomerDdl", #data_val = false })
#Html.ValidationMessageFor(m => m.CustomerNameSelected, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Devices, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.DeviceSelected, Model.Devices, "Select", new { onchange = "this.form.submit();", #class = "form -control form-control-sm", #id = "DeviceDdl", #data_val = false })
#Html.ValidationMessageFor(m => m.DeviceSelected, "", new { #class = "text-danger" })
</div>
</div>
}
#using (Html.BeginForm("SaveData", "ChannelManager", FormMethod.Post))
{
<table class="table table-striped" style="font-size:small;">
<thead>
<tr>
<th>
Channel Name
</th>
<th>
UOM's'
</th>
<th>
Channel UOM
</th>
<th>
Calculated
</th>
<th></th>
</tr>
</thead>
<tbody>
#{ var channelNames = Model.ChannelNames.Select(x => x.ChannelName).OrderByDescending(x => Model.ChannelName).ToList();
for (int count = 0; count < channelNames.Count(); count++)
{
var channel = channelNames[count];
var ddlId = ("ddlId" + count).ToString();
var txtBoxId = ("txtBoxId" + count).ToString();
<tr>
#Html.HiddenFor(x => x.CustomerNameSelected)
#Html.HiddenFor(x => x.DeviceSelected)
<td>
#Html.Label(channel)
</td>
<td>
#Html.DropDownListFor(x => x.UomSelected, Model.Uom, "Select", new { #class = "form-control form-control-sm", #id = #ddlId, #data_val = false })
<script type="text/javascript">
$('##ddlId').change(function () {
$('##txtBoxId').val($(this).val());
});
</script>
</td>
<td>
#Html.EditorFor(x => x.ChannelDataToSave, Model.UomSelected, new { htmlAttributes = new { #id = #txtBoxId, #class = "form-control form-control-sm" } })
#Html.ValidationMessageFor(x => x.ChannelType, "", new { #class = "text-danger" })
</td>
<td>
#Html.CheckBoxFor(x => x.Calculated)
</td>
</tr>
}
}
</tbody>
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-sm btn-primary" />
</div>
</div>
}
</div>
I want to pass all of the data created in the second form back to my Action using the ViewModel:
public class ChannelManagerViewModel
{
[Display(Name = "Select a customer")]
public IEnumerable<SelectListItem> CustomerNames { get; set; }
public string CustomerNameSelected { get; set; }
[Display(Name = "Select a device")]
public IEnumerable<SelectListItem> Devices { get; set; }
public string DeviceSelected { get; set; }
[Display(Name = "Channel Name")]
public string ChannelName { get; set; }
[Display(Name = "Channel Type")]
public string ChannelType { get; set; }
[Display(Name = "Calculated")]
public bool Calculated { get; set; }
public int ChannelCount { get; set; }
public List<ChannelManagerModel> ChannelNames { get; set; }
public List<ChannelManagerViewModel> ChannelDataToSave { get; set; }
private List<string> UomList {
get
{
var l = new List<string>();
l.Add("Electricity");
l.Add("Gas");
l.Add("Water");
l.Add("Heat");
l.Add("kWh");
l.Add("Wh");
l.Add("kVarh");
l.Add("Wh");
l.Add("Volts 1");
l.Add("Volts 2");
l.Add("Volts 3");
l.Add("Current 1");
l.Add("Current 2");
l.Add("Current 3");
l.Add("Hz");
l.Add("Litres");
l.Add("Cubic Metres");
l.Add("Cubic Feet");
return l;
}
}
public IEnumerable<SelectListItem> Uom {
get {
List<SelectListItem> sl = new List<SelectListItem>();
foreach (var item in UomList)
{
sl.Add(new SelectListItem() { Text = item, Value = item });
};
return sl;
}
set { }
}
public string UomSelected { get; set; }
}
I want to then save the data.
I have tried a number of things including using a partial view, but that doesn't work. I have also tried adding the loop index
#Html.EditorFor(x => x[count].ChannelDataToSave, Model.UomSelected, new { htmlAttributes = new { #id = #txtBoxId, #class = "form-control form-control-sm" } })
but this just tells me Cannot apply indexing with [] to an expression of type 'ChannelManagerViewModel'
I was hoping that the form would create a List<ChannelManagerViewModel> to pass back to the Action
[HttpPost]
public ActionResult SaveData(ChannelManagerViewModel vm)
{
//Do some stuff
return View(vm);
}
All it passes back is a null viewmodel.
Can you advise what is wrong with this?
The expected outcome is that when the form is created in the for loop, it creates a List to pass back to the Action in the Controller. Currently it doesn't...
TIA
i'm trying to edit a row (my project is a simple phone book)from my index view which shows all of my records (Contact) but when i click on the edit button nothing happens
this is my delete method
#region [- Delete -]
#region [- Get -]
[HttpGet]
// [HttpDelete]
public ActionResult Delete(int? _id, Models.EF_Model.Phone_book _model)
{
return View();
}
#endregion
#region [- Post -]
[HttpPost]
//[HttpDelete]
public ActionResult Delete(Models.EF_Model.Phone_book _Model)
{
if (ModelState.IsValid)
{
Ref_ViewModel = new ViewModel.ViewModel();
Ref_ViewModel.Delete(_Model.Id);
}
else
{
ViewBag.Massage = "Choose a Contact";
}
return View(_Model);
}
#endregion
#endregion
this is my edit method in my Home controller
[HttpGet]
public ActionResult Edit(int? _id)
{
if (_id==null)
{
return new HttpStatusCodeResult(HttpStatusCode.NoContent);
}
else
{
Ref_ViewModel = new ViewModel.ViewModel();
return View(Ref_ViewModel.Select(_id));
}
}
[HttpPost]
public ActionResult Edit(ViewModel.DTO.Contact Ref_Contact)
{
if (ModelState.IsValid)
{
Ref_ViewModel = new ViewModel.ViewModel();
Ref_ViewModel.Edit(Ref_Contact, Ref_Contact.Id);
}
else
{
ViewBag.Message = "Choose a Contact";
}
return View();
}
this is it's view(Contact class is a simple DTO class)
#model Phone_Book.ViewModel.DTO.Contact
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Contact</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Num, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Num, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Num, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
this is my index view
#model IEnumerable<Phone_Book.Models.EF_Model.Phone_book>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.First_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Last_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Number)
</th>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.First_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Last_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Number)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
In your Edit method in your HomeController, try this:
[HttpGet]
public ActionResult Edit(int? _id)
{
if (_id==null)
{
return new HttpStatusCodeResult(HttpStatusCode.NoContent);
}
else
{
return View();
}
}
From your Home/Index View make a link to edit action of your HomeController
Index.cshtml
#model IEnumerable<Phone_Book.ViewModel.DTO.Contact>
<h1>Welcome!</h1>
#{
ViewBag.Title = "Home";
}
<table>
<thead>
<tr>
<th>Num</th>
<th>FirstName</th>
<th>LastName</th>
<th>Email</th>
<th>Address</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#foreach (var contact in Model)
{
<tr>
<td>#contact.Num</td>
<td>#contact.FName</td>
<td>#contact.LName</td>
<td>#contact.Address</td>
<td>#Html.ActionLink("Edit", "Edit", new {id = contact.Id}) </td>
</tr>
}
</tbody>
</table>