I have a question how to add input fields values with same name into the database using entity framework? Below is my code, - asp.net-mvc

This is my HomeWithIndentityController
namespace MVC.CRUDDynamicFormTest.Controllers
{
public class HomeWithIndentityController : Controller
{
// GET: HomeWithIndentity
public ActionResult WithIndex()
{
return View();
}
public ActionResult GetData()
{
using (DynamicCRUDDatabase2Entities db = new DynamicCRUDDatabase2Entities())
{
List<DynamicCRUDTable2> dynamicCRUDTable2s = db.DynamicCRUDTable2.ToList<DynamicCRUDTable2>();
return Json(new { data = dynamicCRUDTable2s }, JsonRequestBehavior.AllowGet);
}
}
[HttpGet]
public ActionResult Add(int id = 0)
{
return View(new DynamicCRUDTable2());
}
[HttpPost]
public ActionResult Add(DynamicCRUDTable2 obj)
{
using (DynamicCRUDDatabase2Entities db = new DynamicCRUDDatabase2Entities())
{
db.DynamicCRUDTable2.Add(obj);
db.SaveChanges();
return Json(new { succces = true, message = "saved Successfully" }, JsonRequestBehavior.AllowGet);
//return RedirectToAction("Index", "Home");
}
}
}
}
this is my entity model class
public partial class DynamicCRUDTable2
{
public int Id { get; set; }
public string FirstName { get; set; }
}
This my View
<form action="~/HomeWithIndentity/Add" method="POST" onsubmit="return Submitform(this)">
<input data-val="true" id="Id" name="Id" type="hidden" />
<label>First Name</label>
<input type="text" name="FirstName[]" class="form-control" />
<input type="text" name="FirstName[]" class="form-control" />
<br />
<br />
<div>
<input type="submit" value="Submit" class="btn btn-success" />
<input type="reset" value="Reset" class="btn btn-danger" />
<a class="btn btn-danger" href="~/Home/Index">Cancel</a>
</div>
</form>
In the above view i want to add the firstname input field values to the Database dynamicallly.but it does not working can you let me know why?What errors i have done.
does anyone know how to do that?

Related

how can i show the data that the user entered in the file input when he want to edit it

for your information the file is saved as a binary data
here is is the model:
public class Movie
{
[Key]
public int MovieId { get; set; }
public string MovieName { get; set; }
public string MovieDescription { get; set; }
public byte[] MovieImage { get; set; }
public string MovieTrailer { get; set; }
//FK
public int AdminId { get; set; }
//Navigation
public Admin Admin { get; set; }
public ICollection<Event> Events { get; set; }
public AddingCategory AddingCategory { get; set; }
public ViewingMovie ViewingMovie { get; set; }
}
}
And here is the controller :
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var movie = await _context.tblMovies.FindAsync(id);
if (movie == null)
{
return NotFound();
}
ViewData["AdminId"] = new SelectList(_context.Set<Admin>(), "AdminId", "Email", selectedValue: movie.AdminId);
return View(movie);
}
// POST: Movies/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("MovieId,MovieName,MovieDescription,MovieImage,MovieTrailer,AdminId")] Movie movie, IFormFile MovieImage)
{
if (id != movie.MovieId)
{
return NotFound();
}
if (MovieImage != null)
{
//This code is used to copy image to DataBase
using (var myStream = new MemoryStream())
{
await MovieImage.CopyToAsync(myStream);
movie.MovieImage = myStream.ToArray();
}
}
if (ModelState.IsValid)
{
try
{
_context.Update(movie);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MovieExists(movie.MovieId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["AdminId"] = new SelectList(_context.Set<Admin>(), "AdminId", "Email", movie.AdminId);
return View(movie);
}
and the last here is the edit view:
<div class="row">
<div class="col-md-4">
<form asp-action="Edit" method="post" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="MovieId" />
<div class="form-group">
<label asp-for="MovieName" class="control-label"></label>
<input asp-for="MovieName" class="form-control" />
<span asp-validation-for="MovieName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="MovieDescription" class="control-label"></label>
<input asp-for="MovieDescription" class="form-control" />
<span asp-validation-for="MovieDescription" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="MovieImage" class="control-label"></label>
<input asp-for="MovieImage" class="form-control" type="file" />
<span asp-validation-for="MovieImage" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="MovieTrailer" class="control-label"></label>
<input asp-for="MovieTrailer" class="form-control" />
<span asp-validation-for="MovieTrailer" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="AdminId" class="control-label"></label>
<select asp-for="AdminId" class="form-control" asp-items="ViewBag.AdminId"></select>
<span asp-validation-for="AdminId" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
all i want is to show what the user entered in the file input and if he want to edit it or keep as it is.
i have been struggling with this problem in days PLEASE somebody help me out

How do I upload pdf into a folder and store the path into a database, and be able to view the uploaded file? Thank you

Here is my controller code
namespace MyClassWorkApplication.Areas.Admin.Controllers
{
[Area("Admin")]
[Authorize(Roles = "Admin")]
public class ContentController : Controller
{
private readonly ApplicationDbContext _context;
private IWebHostEnvironment _env;
public ContentController(ApplicationDbContext context, IWebHostEnvironment env)
{
_context = context;
_env = env;
}
// GET: Admin/Content/Create
public IActionResult Create(int categoryItemId, int categoryId)
{
Content content = new Content
{
CategoryId = categoryId,
CatItemId = categoryItemId
};
return View(content);
}
// POST: Admin/Content/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Title,HTMLContent,VideoLink,CatItemId,CategoryId,PublicationPdfUrl")] Content content)
{
Profile profile = new Profile();
profile.Title = content.Title;
//loading remaining properties of the model from ViewModel
//uploading file....
string uniqueFileName = null;
if (content.PublicationPdfUrl != null)
{
string folder = "Publications/pdf/";
string serverFolder = Path.Combine(_env.WebRootPath, folder);
uniqueFileName = Guid.NewGuid().ToString() + "_" + content.PublicationPdfUrl.FileName;
string filePath = Path.Combine(serverFolder, uniqueFileName);
content.PublicationPdfUrl.CopyTo(new FileStream(filePath, FileMode.Create));
profile.PublicationPdfUrl = content.PublicationPdfUrl.FileName;
}
if (ModelState.IsValid)
{
content.CategoryItem = await _context.CategoryItem.FindAsync(content.CatItemId);
_context.Add(content);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index), "CategoryItem", new { categoryId = content.CategoryId });
}
return View(content);
}
// GET: Admin/Content/Edit/5
public async Task<IActionResult> Edit(int categoryItemId, int categoryId)
{
if (categoryItemId == 0)
{
return NotFound();
}
var content = await _context.Content.SingleOrDefaultAsync(item => item.CategoryItem.Id == categoryItemId);
content.CategoryId = categoryId;
if (content == null)
{
return NotFound();
}
return View(content);
}
// POST: Admin/Content/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Title,HTMLContent,VideoLink,CategoryId,PublicationPdfUrl")] Content content)
{
if (id != content.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(content);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ContentExists(content.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index), "CategoryItem", new { categoryId = content.CategoryId });
}
return View(content);
}
private bool ContentExists(int id)
{
return _context.Content.Any(e => e.Id == id);
}
}
}
My Second Controller
namespace MyClassWorkApplication.Controllers
{
public class ContentController : Controller
{
private readonly ApplicationDbContext _context;
public ContentController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index(int categoryItemId)
{
Content content = await (from item in _context.Content
where item.CategoryItem.Id == categoryItemId
select new Content
{
Title = item.Title,
VideoLink = item.VideoLink,
HTMLContent = item.HTMLContent,
PublicationPdfUrl = item.PublicationPdfUrl
}).FirstOrDefaultAsync();
return View(content);
}
}
}
This is my Model class (Content). It was reporting error with the IFormFile until I added the [NotMapped] attributes to it before the error disappears. However, It does not add the pdf Url into that database as I wanted.
public class Content
{
public int Id { get; set; }
[Required]
[StringLength(200, MinimumLength = 2)]
public string Title { get; set; }
[Display(Name = "HTML Content")]
public string HTMLContent { get; set; }
[Display(Name = "Video Link")]
public string VideoLink { get; set; }
public CategoryItem CategoryItem { get; set; }
[NotMapped]
public int CatItemId { get; set; }
//Note: This property cannot be
//named CategoryItemId because this would
//interfere with future migrations
//It has been named like this
//so as not to conflict with EF Core naming conventions
[NotMapped]
public int CategoryId { get; set; }
[NotMapped]
public IFormFile PublicationPdfUrl { get; set; }
}
public class Profile
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string HTMLContent { get; set; }
public string VideoLink { get; set; }
public CategoryItem CategoryItem { get; set; }
public int CatItemId { get; set; }
public int CategoryId { get; set; }
[Display(Name = "Upload your publication in pdf format")]
public string PublicationPdfUrl { get; set; }
}
}
This is my Create View
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Content</h4>
<hr />
<div class="row">
<div class="col-md-10">
<form method="post" enctype="multipart/form-data" asp-action="Create">
<input type="hidden" asp-for="CategoryId">
<input type="hidden" asp-for="CatItemId">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="HTMLContent" class="control-label"></label>
<textarea asp-for="HTMLContent" row="10" class="form-control"></textarea>
<span asp-validation-for="HTMLContent" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="VideoLink" class="control-label"></label>
<input asp-for="VideoLink" class="form-control" />
<span asp-validation-for="VideoLink" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PublicationPdfUrl" class="control-label"></label>
<div class="custom-file">
<input asp-for="PublicationPdfUrl" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile">Choose file...</label>
</div>
<span asp-validation-for="PublicationPdfUrl" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary float-right" />
<a asp-controller="CategoryItem" asp-action="Index" asp-route-categoryId="#Model.CategoryId" class="btn btn-outline-primary">Back to List</a>
</div>
</form>
</div>
</div>
This is my Edit View
#{
ViewData["Title"] = "Edit";
}
<h4>Edit</h4>
<h4>Content</h4>
<hr />
<div class="row">
<div class="col-md-10">
<form method="post" enctype="multipart/form-data" asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<input type="hidden" asp-for="CategoryId" />
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="HTMLContent" class="control-label"></label>
<textarea asp-for="HTMLContent" row="10" class="form-control"></textarea>
<span asp-validation-for="HTMLContent" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="VideoLink" class="control-label"></label>
<input asp-for="VideoLink" class="form-control" />
<span asp-validation-for="VideoLink" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PublicationPdfUrl" class="control-label"></label>
<div class="custom-file">
<input asp-for="PublicationPdfUrl" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile">Choose file...</label>
</div>
<span asp-validation-for="PublicationPdfUrl" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary float-right" />
<a asp-controller="CategoryItem" asp-action="Index" asp-route-categoryId="#Model.CategoryId" class="btn btn-outline-primary">Back to List</a>
</div>
</form>
</div>
</div>

InvalidOperationException: Model item passed in the ViewDataDictionary is of type 'System.Object'

I encountered the problem when I was creating a Create page. Which lead me to an error message which says:
Error Message:
Im not entirely sure if my model name is correct.
Below are my following codes:
Songs Controller:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System.Data;
using System.Data.SqlClient;
using System;
using Garcia___MVC.Models;
namespace Garcia___MVC.Controllers
{
public class SongsController : Controller
{
private const string ConnectionString =
#"*";
// GET: SongsController
[HttpGet]
public ActionResult Index()
{
DataTable dtbSongs = new DataTable();
using(SqlConnection sqlCon = new SqlConnection(ConnectionString))
{
sqlCon.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Songs",sqlCon);
sqlDa.Fill(dtbSongs);
}
return View(dtbSongs);
}
// GET: SongsController/Create
[HttpGet]
public ActionResult Create(object model)
{
return View(model);
}
// POST: SongsController/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: SongsController/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: SongsController/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: SongsController/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: SongsController/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
}
}
Create Page that can't be accessed:
#model Garcia___MVC.Models.SongsModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>SongsModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="SongID" class="control-label"></label>
<input asp-for="SongID" class="form-control" />
<span asp-validation-for="SongID" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="SongTitle" class="control-label"></label>
<input asp-for="SongTitle" class="form-control" />
<span asp-validation-for="SongTitle" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Artists" class="control-label"></label>
<input asp-for="Artists" class="form-control" />
<span asp-validation-for="Artists" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Album" class="control-label"></label>
<input asp-for="Album" class="form-control" />
<span asp-validation-for="Album" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
SongsModel.cs
using System;
namespace Garcia___MVC.Models
{
public class SongsModel
{
public int SongID { get; set; }
public string SongTitle { get; set; }
public string Artists { get; set; }
public string Album { get; set; }
}
}
Would appreciate any advice or tips on how I can go about this. Will be very much appreciated.
I was expecting a page which you can create the Song title, Artists, Album, and Song ID.
The return type of the action in the songsController must be SongsModel.
The type you specify at the top of the view page determines the return type.
I'm sorry for my bad english.

Passing values of checkboxes from View to Controller

I have a view with a number of checkboxes in it. I want to be able to pass the values of the checkboxes to the controller, then output a list of the OfficeNames that have been ticked. I am not sure how to pass the values of multiple checkboxes back to the controller, or how to output the OfficeNames based on which boxes have been ticked
View:
<p>
#using (Html.BeginForm())
{
<p>
Start Date: #Html.TextBox("StartDate") <br />
<br />
End Date: #Html.TextBox("EndDate") <br />
<br />
<input type="submit" value="Filter" />
</p>
}
<p>
#foreach (var item in Model.BettingOffices)
{
<label>#Html.DisplayFor(modelItem => item.OfficeName)</label>
<input type="checkbox" name="selectedShops" value="#item.OfficeName">
}
</p>
Controller:
public class DailyReportController : Controller
{
private RiskEntities _db = new RiskEntities();
// GET: /DailyReport/
public ActionResult Index(DateTime? startDate, DateTime? endDate)
{
if (startDate == null || endDate == null)
{
var dailyReportModelBlank = new DailyReportModel();
dailyReportModelBlank.BettingOffices = (from bo in _db.BettingOffices orderby bo.OfficeName select bo ).ToList();
//dailyReportModelBlank.DailyReports.Add(new DailyReport());
return View(dailyReportModelBlank);
}
var endDateToUse = (DateTime) endDate;
endDateToUse = endDateToUse.AddDays(+1);
var dailyReportModel = new DailyReportModel
{
DailyReports = (from dr in _db.DailyReports
where dr.DailyReportDate >= startDate
&& dr.DailyReportDate <= endDateToUse
select dr).ToList(),
BettingOffices = (from bo in _db.BettingOffices select bo).ToList()
};
return View(dailyReportModel);
}
Model:
public class DailyReportModel
{
private List<DailyReport> _dailyReports = new List<DailyReport>();
private List<BettingOffice> _bettingOffices = new List<BettingOffice>();
public List<DailyReport> DailyReports
{
get { return _dailyReports; }
set { _dailyReports = value; }
}
public List<BettingOffice> BettingOffices
{
get { return _bettingOffices; }
set { _bettingOffices = value; }
}
}
BettingOffice Class:
public partial class BettingOffice
{
public int BettingOfficeID { get; set; }
public string OfficeName { get; set; }
public string OfficeCode { get; set; }
public string IpAddress { get; set; }
public Nullable<bool> SupportOnly { get; set; }
public Nullable<int> SisSrNumer { get; set; }
public Nullable<bool> Local { get; set; }
public string Server { get; set; }
}
try this :
<p>
#using (Html.BeginForm())
{
<p>
Start Date: #Html.TextBox("StartDate")
<br />
<br />
End Date: #Html.TextBox("EndDate")
<br />
<br />
<input type="submit" value="Filter" />
</p>
}
</p>
<p>
#foreach (var item in Model.BettingOffices)
{
<label>#Html.DisplayFor(modelItem => item.OfficeName)</label>
<input type="checkbox" name="bettingOfficeIDs" value="#item.BettingOfficeID">
}
</p>
And in your Action you can get the selected office ids in bettingOfficeIDs variable:
public ActionResult YourActionName(int[] bettingOfficeIDs)
Few things that need to change here.
If you want values to be passed to action method they need to be within form not outside
For MVT to 'understand' checkbox values as array (or more complex object) you need to work with their html name attribute.
I will do demonstration application below that should help you understand how it works:
CsHtml: Notice that you need to add value attribute to checkboxes to be able to read their values, checkbox gets true only when checkbox is ticked and value is true, hence the javascript. You can add as many of complex object properties as hidden fields as long as you give them names that match to the object property names in viewModel. In this case I am only passing BettingOfficeID
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(document).on("click", "[type='checkbox']", function(e) {
if (this.checked) {
$(this).attr("value", "true");
} else {
$(this).attr("value","false");}
});
<p>
#using (Html.BeginForm())
{
<p>
Start Date: #Html.TextBox("StartDate") <br />
<br />
End Date: #Html.TextBox("EndDate") <br />
<br />
</p>
<p>
<input type="checkbox" name="BettingOffices[0].Selected" value="true">
<input type="hidden" name="BettingOffices[0].BettingOfficeID" value="1">
<input type="checkbox" name="BettingOffices[1].Selected" value="false">
<input type="hidden" name="BettingOffices[1].BettingOfficeID" value="2">
<input type="checkbox" name="BettingOffices[2].Selected" value="true">
<input type="hidden" name="BettingOffices[2].BettingOfficeID" value="3">
<input type="checkbox" name="BettingOffices[3].Selected" value="false">
<input type="hidden" name="BettingOffices[3].BettingOfficeID" value="4">
<input type="checkbox" name="BettingOffices[4].Selected" value="true">
<input type="hidden" name="BettingOffices[4].BettingOfficeID" value="5">
</p>
<input type="submit" value="submit"/>
}
Post Action method to add to controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(BettingViewModel viewModel)
{
return null;
}
BettingViewModel: I have added Selected property to BettingOffice class.
public class BettingViewModel
{
public string StartDate { get; set; }
public string EndDate { get; set; }
public List<BettingOffice> BettingOffices { get; set; }
}
public class BettingOffice
{
public bool Selected { get; set; }
public int BettingOfficeID { get; set; }
public string OfficeName { get; set; }
public string OfficeCode { get; set; }
public string IpAddress { get; set; }
public Nullable<bool> SupportOnly { get; set; }
public Nullable<int> SisSrNumer { get; set; }
public Nullable<bool> Local { get; set; }
public string Server { get; set; }
}
Hope this saves you some time.
View:
#using (Html.BeginForm("Createuser", "User", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<div class="form-group">
#Html.LabelFor(m => m.city, new { #class = "col-md-2 control-label" })
</div>
<div class="col-md-10">
<table>
<tr>
<td><input type="checkbox" name="city" value="Pune" id="1" />Pune</td>
<td><input type="checkbox" name="city" value="Banglore" id="2" />Banglore</td>
<td><input type="checkbox" name="city" value="Mumbai" id="3" />Mumbai</td>
</tr>
</table>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Create" />
</div>
</div>
}
[HttpPost]
public ActionResult Createuser(user user, string [] city)
{
var UserInfo = new user
{ Email =user.Email,Password=user.Password,Firstname=user.Firstname };
return View();
}
1. First of all, you are generating checkboxes with same name. So how you will be able to retrieve them on server end separately?
So declare some counter that gets incremented and name checkboxes uniquely.
#foreach (var item in Model.BettingOffices)
{
int counter=1;
var checkboxName = "selectedShops" + counter;
<label>#Html.DisplayFor(modelItem => item.OfficeName)</label>
<input type="checkbox" name="#checkboxName" value="#item.OfficeName">
counter++;
}
2. Now on submission of Form in your controller, get checkboxes as -
//Loop through the request.forms
for (var i = 0; i <= Request.Form.Count; i++)
{
var checkboxValue = Request.Form["selectedShops[" + i + "]"];
// Do whatever you want to with this checkbox value
}
For ticked values, you will probably get True value. Debug the retrieved value to write further code accordingly.
Try the following
your View is:
#foreach (var item in Model.BettingOffices)
{
<label>#Html.DisplayFor(modelItem => item.OfficeName)</label>
<input type="checkbox" name="selectedShops" value="#item.OfficeName">
}
Controller
[HttpPost]
public ActionResult Index(FormCollection collection)
{
if(!string.IsNullOrEmpty(collection["selectedShops"]))
{
string strSelectedShops = collection["selectedShops"];
}
}
Hi you can get the selected checkbox value using the bellow code it seem working fine fore me,
<script>
$(document).ready(function()
{
$("input[type=checkbox]").click(function()
{
var categoryVals = [];
categoryVals.push('');
$('#Category_category :checked').each(function() {
categoryVals.push($(this).val());
});
$.ajax({
type:"POST",
url:"<?php echo $this->createUrl('ads/searchresult'); ?>", //url of the action page
data:{'category': categoryVals},
success : function(response){
//code to do somethng if its success
}
});
}
}
</script>

Stack trace error

I am having the error message:I can`t figure out what is wrong. Can someone help me please. Thanks.
Stack Trace:
[NotSupportedException: Collection is
read-only.]
System.SZArrayHelper.Clear() +56
System.Web.Mvc.CollectionHelpers.ReplaceCollectionImpl(ICollection`1
collection, IEnumerable newContents)
+125
ExecuteStep(IExecutionStep step,
Boolean& completedSynchronously) +184
My code is:
Model:
namespace TestArrays.Models
{
public class Person
{
public CategoriesRow[] Categories { get; set; }
public Person()
{
Categories = new CategoriesRow[1];
Categories[0] = new CategoriesRow();
Categories[0].Name = "Bug";
Categories[0].ID = "0";
}
}
public class CategoriesRow
{
public String Name { get; set; }
public String ID { get; set; }
}
}
Controller
public ActionResult Create()
{
return View(new Person());
}
//
// POST: /Person/Create
[HttpPost]
public ActionResult Create(Person person)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Views
<form id="Form" action="<%=Url.Action("Create",new{Action="Create"}) %>" method="post" enctype="multipart/form-data">
<div id="categoriessection" >
<h3>Categories</h3>
<ul class= "list" id="categoryList">
<%if (Model.Categories!=null) {%>
<%int count = 0; %>
<%foreach (var category in Model.Categories)
{%>
<%if (!String.IsNullOrEmpty(category.Name))
{%>
<li><input type="hidden" name="Categories.Index" value="<%=count%>" />
<input type="text" value="<%=category.Name%>" name="Categories[<%=count%>].Name" style="width:280px"/>
<input type="hidden" value="<%=category.ID%>" name="Categories[<%=count++%>].ID" style="width:280px"/>
<input type="button" value = "Delete"/>
</li>
<%}
%>
<%} %>
<%} %>
<li> <input type="hidden" name="Categories.Index" value="value0" />
<input type="text" value="" name="Categories[value0].Name" style="width:280px"/>
<input type="hidden" value="" name="Categories[value0].ID" style="width:280px"/>
<input type="button" value= "Add" />
</li>
</ul>
</div>
<div>
<input type ="submit" value="Save" id="save" />
</div>
</form>
I usually use lists instead of vectors in models:
public List<CategoriesRow> Categories { get; set; }

Resources