How to pass selected Checkbox items to Controller in MVC? - c#

I have the code below and when I click on submit the list contains all possible models. However, I only want to know the models which have an checkbox selected. How do I do this?
The issue is that Index containts the whole List, but I only want to have the models or selected items from the ones that are selected in the checkbox. In the scenario below I'm also using some hiddenfields to fill the model. Any advice how I can pass the selections to the controller?
HomeController
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using WebApp.Models;
namespace WebApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
var viewModel = new MainViewModel()
{
SomeInfo = "test",
SomeModel = new SomeModel
{
Name = "Model1",
SomeType1 = new List<SomeType1>
{
new SomeType1 { Id = "1", Name = "Spinach", Value = "TXT_FLD_SPINA", ExtraInfo = "something1" },
new SomeType1 { Id = "2", Name = "Broccoli", Value = "TXT_FLD_BRO", ExtraInfo = "something else5" },
new SomeType1 { Id = "3", Name = "Wheatgrass", Value = "TXT_FLD_WHE", ExtraInfo = "something else4" },
},
SomeOtherType2 = new List<SomeType1>
{
new SomeType1 { Id = "1", Name = "Apple", Value = "TXT_FLD_APPLE", ExtraInfo = "something" },
new SomeType1 { Id = "2", Name = "Banana", Value = "TXT_FLD_BANA", ExtraInfo = "something else" },
new SomeType1 { Id = "3", Name = "Tomatoes", Value = "TXT_FLD_TOM", ExtraInfo = "something else2" },
}
}
};
return View(viewModel);
}
[HttpPost]
public IActionResult Index(string search, List<SomeType1> SomeType1, string[] SomeOtherType2)
{
return View();
}
}
}
MainViewModel
using System.Collections.Generic;
namespace WebApp.Models
{
public class MainViewModel
{
public SomeModel SomeModel { get; set; }
public string SomeInfo { get; set; }
}
public class SomeModel
{
public List<SomeType1> SomeType1 { get; set; }
public List<SomeType1> SomeOtherType2 { get; set; }
public string Name { get; set; }
}
public class SomeType1
{
public string Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public string ExtraInfo { get; set; }
}
}
Index.cshtml
#model MainViewModel
#{
ViewData["Title"] = "Home Page";
}
#using (Html.BeginForm("Index", "Home"))
{
<div class="text-center">
<input type="text" name="search" />
<input type="submit" value="Submit" />
</div>
<br />
for (int i = 0; i < Model.SomeModel.SomeType1.Count; i++)
{
<b>Some Type 1</b>
<div class="checkbox">
<label>
<input type="checkbox"
name="SomeType1[#i].Value"
value="#Model.SomeModel.SomeType1[i].Value" /> #Model.SomeModel.SomeType1[i].Name
</label>
</div>
}
for (int i = 0; i < Model.SomeModel.SomeOtherType2.Count; i++)
{
<b>SomeOtherType2</b>
<div class="checkbox">
<label>
<input type="checkbox"
name="SomeOtherType2"
value="#Model.SomeModel.SomeOtherType2[i].Value" /> #Model.SomeModel.SomeOtherType2[i]..Name
</label>
</div>
}
}

Related

Partial view data doesn't get saved in ASP.NET Core MVC

I create class Project in project class I define technology and another i define Class Technology I seed data in technology and after that i create dropdown list in Project Create view using a partial view and when I save data the technology can not be saved
public class Project
{
public int ProjectId { get; set; }
[StringLength(60, MinimumLength = 3)]
public string? ProjectName { get; set; }
public string? Description { get; set; }
public DateTime Start { get; set; }
public DateTime? End { get; set; }
public string? ProjectHead { get; set; }
public string? Status { get; set; }
public string? Technology { get; set; }
}
public class Technology
{
public int TechnologyId { get; set; }
public string? TechnologyName { get; set; }
}
This is my controller:
public async Task<IActionResult> Create([Bind("ProjectId,ProjectName,Description,Start,End,ProjectHead,Status,Technology")] Project project)
{
if (ModelState.IsValid)
{
_context.Add(project);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(project);
}
This is my view of project create:
<div class="row">
<partial name="_Technologypartial" />
</div>
technology Patial
#model TeamManagement.Models.Technology
<div class="row">
<div class="form-group col-md-6">
<label>Technology</label>
<br />
<select asp-for="TechnologyId" class="form-control" asp-items="#(new SelectList(ViewBag.Technology,"TechnologyId","TechnologyName"))">
</select>
</div>
</div>
EDIT
View
<div class="row">
<partial name="_Technologypartial" model="#Model.technology" />
</div>
Controller
{
var list = _context.Technology.ToList();
List<SelectListItem> dropdown = new List<SelectListItem>();
foreach (var item in list)
{
dropdown.Add(new SelectListItem()
{
Text = item.TechnologyName,
Value = item.TechnologyId.ToString()
});
}
PartialViewData model = new PartialViewData();
ViewBag.Technology = dropdown;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(PartialViewData model)
{
if (ModelState.IsValid)
{
Project project = new Project()
{
ProjectId = model.project.ProjectId,
ProjectName = model.project.ProjectName,
Description = model.project.Description,
Start = model.project.Start,
End = model.project.End,
ProjectHead = model.project.ProjectHead,
Status = model.project.Status,
Technology = model.technology.TechnologyId.ToString()
};
_context.Add(project);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(model);
}
When you select an option in Partial View, After submiting the form, You want save the value of option. I suggest you to use ViewModel to achieve it. Refer to this simple demo:
I simplified your class for testing convenience.
public class Project
{
public string Name { get; set; }
public string? Technology { get; set; }
}
public class Technology
{
public int TechnologyId { get; set; }
public string? TechnologyName { get; set; }
}
Create a View model to pass the value.
public class PartialViewData
{
public PartialViewData()
{
project = new Project();
technology = new Technology();
}
public Project project { get; set; }
public Technology technology { get; set; }
}
DbContext
public class MvcMovieContext : DbContext
{
public MvcMovieContext(DbContextOptions<MvcMovieContext> options) : base(options)
{
}
public DbSet<Technology> technology { get; set; }
}
Controller
public class HomeController : Controller
{
private readonly MvcMovieContext _context;
public HomeController(MvcMovieContext context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
var list = _context.technology.ToList();
List<SelectListItem> dropdown = new List<SelectListItem>();
foreach(var item in list)
{
dropdown.Add(new SelectListItem()
{
Text = item.TechnologyName,
Value = item.TechnologyId.ToString()
}) ;
}
PartialViewData model = new PartialViewData();
ViewBag.Technology = dropdown;
return View(model);
}
[HttpPost]
public IActionResult Privacy(PartialViewData model)
{
Project project = new Project()
{
Name = model.project.Name,
Technology = model.technology.TechnologyId.ToString()
};
//......
return View();
}
}
View
#model PartialViewData
<form method="post">
<input asp-for="#Model.project.Name" />
<div class="row">
<partial name="_Technologypartial" model="#Model.technology" />
</div>
<button type="submit">submit</button>
</form>
_Technologypartial
#model Technology
<div class="row">
<div class="form-group col-md-6">
<label>Technology</label>
<br />
<select name="technology.TechnologyId" class="form-control" asp-items=#ViewBag.Technology>
</select>
</div>
</div>
Demo:
Edit=================
public IActionResult Create()
{
var list = _context.technology.ToList();
List<SelectListItem> dropdown = new List<SelectListItem>();
foreach(var item in list)
{
dropdown.Add(new SelectListItem()
{
Text = item.TechnologyName,
Value = item.TechnologyId.ToString()
}) ;
}
PartialViewData model = new PartialViewData();
ViewBag.Technology = dropdown;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(PartialViewData model)
{
if (ModelState.IsValid)
{
//change here
var name = _context.Technology.Where(x => x.TechnologyId == model.technology.TechnologyId).Select(x => x.TechnologyName).FirstOrDefault();
Project project = new Project()
{
ProjectId = model.project.ProjectId,
ProjectName = model.project.ProjectName,
Description = model.project.Description,
Start = model.project.Start,
End = model.project.End,
ProjectHead = model.project.ProjectHead,
Status = model.project.Status,
//change here
Technology = name
};
_context.Add(project);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(model);
}
View
#model PartialViewData
<div class="row">
<partial name="_Technologypartial" model="#Model.technology" />
</div>
_Technologypartial
#model Technology
<div class="row">
<div class="form-group col-md-6">
<label>Technology</label>
<br />
<select name="technology.TechnologyId" class="form-control" asp-items=#ViewBag.Technology>
</select>
</div>
</div>

DropdownList is giving a null value to controller calling model

I am a student developer in ASP.NET. I have a question which i did not find a solution about it. I can build a form for my controller. i am taking a value from my input objects but i am not taking value from dropdown list to my controller. It gives null value on my controller. Could you help me about where i made a mistake?
My View Model :
public class CountryViewModel
{
public IEnumerable<Country> CountryList { get; set; }
public Country Country;
}
My controller :
public ActionResult Index()
{
var model = new CountryViewModel()
{
CountryList = db.Country.ToList()
};
return View(model);
}
[HttpPost]
public ActionResult Index(string timeForCheckedOut,CountryViewModel cvModel)
{
return View();
}
my index.cshtml:
#model PenaltyCalculation.Models.ViewModel.CountryViewModel
<form class="" style="margin-top:10%;" action="/" method="post">
<div class="form-group">
<label>Check out date of the Book</label>
<input class="form-control" type="date" name="timeForCheckedOut">
</div>
<div class="form-group">
<label>Choose a country</label>
#Html.DropDownListFor(m=>m.Country.countryId,new SelectList(Model.CountryList,"countryId","countryName"),new {#class="form-control" })
</div>
<button type="submit" class="btn btn-primary">Calculate</button>
</form>
My Country Model:
public partial class Country
{
public int countryId { get; set; }
public string countryName { get; set; }
}
Option #1:
You just need to put the { get; set; } on the end of Country in your CountryViewModel. This will allow you to set the countryId value, but the name will not be set. You will have to look that up from your db if you need that also.
public class CountryViewModel
{
public IEnumerable<Country> CountryList { get; set; }
public Country Country { get; set; }
}
Option #2
This is what I would do. Remake your CountryViewModel to actually represent your View's Model.
public class CountryViewModel
{
public int CountryID { get; set; }
public DateTime TimeForCheckedOut { get; set; }
}
Then update your controller.
// Simulating a db
private List<Country> Countries;
public HomeController()
{
// Initializing sample data
Countries = new List<Country>();
Countries.Add(new Country() { countryId = 1, countryName = "USA" });
Countries.Add(new Country() { countryId = 2, countryName = "England" });
Countries.Add(new Country() { countryId = 3, countryName = "Japan" });
Countries.Add(new Country() { countryId = 4, countryName = "China" });
}
public ActionResult Index()
{
// I prefer using the ViewData Dictionary for my selectlists
ViewData["CountrySelectList"] = new SelectList(Countries, "countryId", "countryName");
return View();
}
[HttpPost]
public ActionResult Index(CountryViewModel cvModel)
{
var country = Countries.First(c => c.countryId == cvModel.CountryId);
// Do Stuff Like Saving and Updating
ViewData["CountrySelectList"] = new SelectList(Countries, "countryId", "countryName", cvModel.CountryId);
return View(cvModel);
}
And Finally update your View
#model PenaltyCalculation.Models.ViewModel.CountryViewModel
<form class="" style="margin-top:10%;" action="/" method="post">
<div class="form-group">
<label>Check out date of the Book</label>
<input class="form-control" type="date" name="timeForCheckedOut">
</div>
<div class="form-group">
<label>Choose a country</label>
#Html.DropDownListFor(m => m.CountryId, (SelectList)ViewBag.CountrySelectList, new { #class = "form-control" })
</div>
<button type="submit" class="btn btn-primary">Calculate</button>
</form>
public class CountryController : Controller
{
// GET: Country
public ActionResult Index()
{
var model = new CountryViewModel()
{
CountryList = GetCountries()
};
return View(model);
}
[HttpPost]
public ActionResult Index(CountryViewModel model)
{
model.CountryList = GetCountries();
return View(model);
}
private IEnumerable<Country> GetCountries()
{
return new Country[]
{
new Country()
{
CountryID = 1,
CountryName = "USA"
},
new Country()
{
CountryID = 2,
CountryName = "Mexico"
},
};
}
}
public class CountryViewModel
{
public IEnumerable<Country> CountryList { get; set; }
public int CountryID { get; set; }
public DateTime? TimeForCheckedOut { get; set; }
}
public partial class Country
{
public int CountryID { get; set; }
public string CountryName { get; set; }
}
<form class="" style="margin-top:10%;" action="/Country/Index" method="post">
<div class="form-group">
<label>Check out date of the Book</label>
<input class="form-control" type="date" name="TimeForCheckedOut">
</div>
<div class="form-group">
<label>Choose a country</label>
#Html.DropDownListFor(m => m.CountryID, new SelectList(Model.CountryList, "CountryID", "CountryName"), new { #class = "form-control" })
</div>
<button type="submit" class="btn btn-primary">Calculate</button>
</form>
This is working for me
Make sure CountryID has getter and setter. Also in C# public property name starts with Capital letter (by convention)
I would also suggest, don't bind Country entity directly to view. You may want to create CountryModel

Getting Checkbox Value and Text in Controller

Model
public class AllControls
{
public List<Group> getChkItems { get; set; }
public bool chk { get; set; }
}
public class Group
{
public int ID { get; set; }
public string Name { get; set; }
}
Controller:
[HttpGet]
public ActionResult Index()
{
List<Group> li = new List<Group>()
{
new Group() { ID = 1, Name = "C#" },
new Group() { ID = 1, Name = "Asp.NET" },
new Group() { ID = 1, Name = "SQL" }
};
AllControls model = new AllControls();
model.getChkItems = li;
return View(model);
}
[HttpPost]
public ActionResult Index(AllControls e)
{
return View(e);
}
View:
#using (Html.BeginForm())
{
foreach (var x in #Model.getChkItems)
{
#Html.CheckBoxFor(m => m.chk, new { value = #x.ID }) #x.Name
<br />
}
<input type="submit" value="Submit" id="btn" />
}
How can I get the selected checkbox value and text in the controller?
Here goes my solution. Let your model be as shown below.
public class CheckboxModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
}
public class MainModel
{
public List<CheckboxModel> CheckBoxes { get; set; }
}
And let your Controller GET Action be as shown below.
public ActionResult GetDatas()
{
MainModel model = new MainModel();
var list = new List<CheckboxModel>
{
new CheckboxModel{Id = 1, Name = "India", Checked = false},
new CheckboxModel{Id = 2, Name = "US", Checked = false},
new CheckboxModel{Id = 3, Name = "UK", Checked = false}
};
model.CheckBoxes = list;
return View(model);
}
And POST Action be as shown below.
[HttpPost]
public ActionResult PostDatas(MainModel model)
{
return View(model);
}
The View should be as shown below.
#model WebApplication1.Controllers.MainModel
#using (Html.BeginForm("PostDatas","Home"))
{
for (var i = 0; i < Model.CheckBoxes.Count; i++)
{
<table>
<tr>
<td>
#Html.HiddenFor(m => Model.CheckBoxes[i].Id)
#Html.HiddenFor(m => Model.CheckBoxes[i].Name)
#Html.CheckBoxFor(m => Model.CheckBoxes[i].Checked)
</td>
<td>
#Html.DisplayFor(m => Model.CheckBoxes[i].Name)
</td>
</tr>
</table>
}
<input id="submit" type="submit" value="submit" />
}
View will be rendered as shown below.
When you select India and US and click on submit button, you will get POST parameters as below.

get selected value from #HtmlDropDown

So i get values for my drop down list but i wanted to get selected value from this dropdown. How to do this ?
Model:
public partial class Region
{
public int Id_regionu { get; set; }
public string Nazwa { get; set; }
}
Controller:
public class HomeController : Controller
{
private inzS9776Entities db = new inzS9776Entities();
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
public ActionResult Index()
{
ViewBag.Regiony = new SelectList(db.Region,"Id_regionu", "Nazwa");
return View();
}
and View with dropdown:
<div class="jumbotron">
<legend>
<h2>Wyszukaj wycieczkÄ™</h2></legend><br/>
<form action="">
<div class="container">
Wybierz kierunek:
#Html.DropDownList("Regiony",null, String.Empty)<br />
Data wyjazdu:
<input class="date" type="date" name="startDate"><br><br>
</div>
</form>
`
Replace your <form action=""> to:
#using (Html.BeginForm("MyActionName") {
// ...
//here add to your dropdown and give it a name
#Html.DropDownList("Regiony", null, String.Empty)
// ...
}
The name attribute of your <select> element (dropdown list) will be "Regiony".
In your controller:
public ActionResult MyActionName(string Regiony) {
// here Regiony variable contains the selected value.
// ...
}
Here is an approach which I take;
1) Retreive the items and store it in a list of SelectListItem.
2) Use the list of SelectListItem to assign it to a drop down list.
3) Use the model field to bind the drop down list with the selected value
View
<div class="col-sm-8">
#{
List<SelectListItem> listItems = new List<SelectListItem>();
foreach (LookupData l in Model.HeatingTypeData)
{
listItems.Add(new SelectListItem { Text = l.LookupDescription, Value = l.LookupCode });
}
}
#Html.DropDownListFor(m => m.HeatingType, listItems, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.HeatingType)
</div>
Models:
The model (VoidProperty) used in the example contains the HeatingType as a List of LookupData and a method to get the list:
public List<LookupData> HeatingTypeData { get; set; }
public static List<LookupData> GetHeatingType()
{
return LookupData.GetDataList("HeatingType").OrderBy(m => m.SortOrder).ToList();
}
and then the LookupData:
public class LookupData : ILookup
{
public string LookupCode { get; set; }
public string LookupDescription { get; set; }
public int SortOrder { get; set; }
public static List<LookupData> GetDataList(string LookupGroup)
{
DBContexts.VoidsDBContext context = new DBContexts.VoidsDBContext();
var Params = new SqlParameter { ParameterName = "LookupGroup", Value = LookupGroup };
return context.Database.SqlQuery<LookupData>("p_LookupList #LookupGroup", Params).ToList();
}
}
The controller returns the view and pass an instance of the model;
VoidProperty _property = new VoidProperty();
......
......
_property.HeatingTypeData = VoidProperty.GetHeatingType();
......
return View(_property);

Writing a list to database

For a school assignment I need to make a poll with ASP.NET
The problem I get when trying to write the answers in the database is that only one question and one answer gets written into it.
This is the View
#model CinemaJamV2.WebUIV2.Models.EnqueteModel
#{
ViewBag.Title = "Enquete";
}
<h2>Enquete</h2>
#Html.ValidationSummary(true)
#using (Html.BeginForm("Enquete", "Enquete", new { vraag = "vraag", antwoord = "antwoord", naam = "naam", cijfer = "cijfer" }))
{
<div class="col-md-12">
#for(var i=0;i< Model.enquetevragen.Count();i++)
{
<div class="thumbnail">
#Html.LabelFor(model => model.enquetevragen[i].vraag, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.enquete.antwoord, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.enquete.cijfer, new { htmlAttributes = new { #class = "form-control" } })
</div>
}
</div>
<div class="col-md-12">
<p>Naam <input type="text" name="naam" /> </p>
<input type="submit" name="submit" value="Verzend" />
</div>
}
This is the Controller:
namespace CinemaJamV2.WebUIV2.Controllers
{
public class EnqueteController : Controller
{
private IRepository<Enquete> repository;
private IRepository<EnqueteVraag> a_repository;
private CineJamContext db = new CineJamContext();
public EnqueteController(IRepository<Enquete> a_model, IRepository<EnqueteVraag> vraag_model)
{
repository = a_model;
a_repository = vraag_model;
}
[HttpGet]
public ActionResult Enquete()
{
EnqueteModel enquetevragen = new EnqueteModel
{
enquetevragen = a_repository.List
};
return View(enquetevragen);
}
[HttpPost]
public ActionResult Enquete(Enquete enquete)
{
if (ModelState.IsValid)
{
db.Enquetes.Add(enquete);
db.SaveChanges();
return RedirectToAction("Enquete");
}
return View(enquete);
}
}
}
The ModelView:
namespace CinemaJamV2.WebUIV2.Models
{
public class EnqueteModel
{
public List<Enquete> enquetes {get; set;}
public Enquete enquete { get; set; }
public List<EnqueteVraag> enquetevragen { get; set; }
}
}
And this is the Model Enquete which should contain all the given answers:
namespace CinemaJamV2.Domain.Entities
{
[Table("Enquete")]
public partial class Enquete : IEntity
{
public int Id { get; set; }
[StringLength(1000)]
public string vraag { get; set; }
[StringLength(1000)]
//[Required]
public string antwoord { get; set; }
public int? cijfer {get; set;}
[StringLength(50)]
//[Required]
public string naam { get; set; }
}
}
This Model contains all the Questions
namespace CinemaJamV2.Domain.Entities
{
[Table("EnqueteVraag")]
public partial class EnqueteVraag : IEntity
{
public int Id { get; set; }
[StringLength(1000)]
public string vraag { get; set; }
}
}
The action for POST has only one instance of the Model as its parameter. You need to read this: Model binding to a list
YOu need to use view model that will have list of Enquete and then in post method again you need to do for loop and save it to database.
See following links for samples.
http://www.binaryintellect.net/articles/b1e0b153-47f4-4b29-8583-958aa22d9284.aspx
http://www.c-sharpcorner.com/UploadFile/pmfawas/Asp-Net-mvc-how-to-post-a-collection/
http://www.codeproject.com/Tips/855577/List-of-Model-Object-Post-to-Controller-in-ASP-NET

Categories

Resources