Making checkboxlist custom validation in asp.net mvc 5 - asp.net

I am developing an ASP.Net MVC 5 Web application and I am having some difficulties with making custom validation on Checkbox list. Validation I need that at least one checkbox must be checked
My ViewModel
public class EditUtilisateurViewModel
{
public long Id { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = " Required ")]
[Display(Name = "Login")]
public string UserName { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Required")]
[Display(Name = "Email")]
[EmailAddress (ErrorMessage = "Invalid Email")]
public string Email { get; set; }
[CheckOneSelected(ErrorMessage = "Please select role")]
public IEnumerable<System.Web.Mvc.SelectListItem> RolesList { get; set; }
}
My Controller
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Id,UserName,Email")] EditUtilisateurViewModel editUser, params string[] selectedRole)
{
if (ModelState.IsValid)
{
// ToDo ...
return RedirectToAction("Index");
}
}
My View
#model MyProject.Areas.Admin.Models.EditUtilisateurViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(m => m.Id)
<table
<tbody>
< >
<th>
#Html.LabelFor(m => m.UserName)
</th>
<td>
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</td>
</tr>
<tr>
<th>
#Html.LabelFor(m => m.Email)
</th>
<td>
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", #disabled = "disabled" })
#*#Html.ValidationMessageFor(m => m.Email)*#
</td>
</tr>
<tr>
<th>#Html.Label("Roles")</th>
<td>
<span>
#foreach (var item in Model.RolesList)
{
#*<input type="checkbox" id="#item.Value" name="SelectedRole" value="#item.Value" checked="#item.Selected" class="checkbox-inline" />*#
#Html.CheckBoxFor(m => item.Selected, new { id = item.Value, #Value = item.Value, #Name = "selectedRole[]", #class = "checkbox-inline", data_val = "true", data_val_verifListe = " Select field " })
#Html.Label(item.Value, new { #class = "checkbox-inline-label" })
}
</span>
#Html.ValidationMessageFor(m => m.RolesList)
</td>
</tr>
</tbody>
</table>
<p>
<input type="submit" value="Update" />
</p>
}
I tried Validation like below but and have essues
namespace ...
{
public class CheckOneSelectedAttribute : ValidationAttribute, IClientValidatable
{
public string[] SelectedRole { get; private set; }
public CheckOneSelectedAttribute(string SelectedValue) : base("Select field")
{
if (SelectedValue != null && SelectedValue.Length > 0)
SelectedRole = SelectedValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
if (selectedRole != null)
{
if (selectedRole.Length == 0)
{
return new ValidationResult("Select field ");
}
}
}
else
{
return new ValidationResult("Null parameter");
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule()
{
ErrorMessage = ErrorMessageString,
ValidationType = "CheckOneSelected"
};
}
}
}
Can some one please help me?
Thanks.

In the controller part which is post and takes []list , You should check the length of the list by that u can make a validation for that .

Related

Dropdown Data Binding Problem in ASP.NET Core 6 MVC

I am using SelectListItem in the controller for binding my dropdown data. All the dropdown options are showing perfectly in the dropdown list, but when I try to save, the problem occurs. It's not adding the dropdown options data rather than its adding dropdown data's id.
All the related models, controller and views are shown here:
BuyerSelectList model class:
public class BuyerSelectList
{
[Key]
public int Id { get; set; }
[DisplayName("BUYER")]
public string Buyer { get; set; }
}
ItemSelectList model class:
public class ItemSelectList
{
[Key]
public int Id { get; set; }
[DisplayName("ITEM")]
public string Item { get; set; }
}
BTBNewLien2 model class:
public class BTBNewLien2
{
public int Id { get; set; }
[Required]
[DisplayName("Buyer")]
public int BuyerSelectListId { get; set; }
[ForeignKey("BuyerSelectListId")]
[ValidateNever]
public BuyerSelectList BuyerSelectList { get; set; }
[Required]
[DisplayName("Item")]
public int ItemSelectListId { get; set; }
[ForeignKey("ItemSelectListId")]
[ValidateNever]
public ItemSelectList ItemSelectList { get; set; }
}
BTBNewLien2 controller (here I added all the data binding functionalities for my dropdown):
namespace CommercialCalculatorWeb.Areas.Admin.Controllers
{
public class BTBNewLien2Controller : Controller
{
private readonly IUnitOfWork _unitOfWork;
public BTBNewLien2Controller(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public IActionResult Index()
{
IEnumerable<BTBNewLien2> objBTBNewLienList = _unitOfWork.BTBNewLien2.GetAll();
return View(objBTBNewLienList);
}
public IActionResult Create()
{
BTBNewLien2 btbNewLien2 = new();
IEnumerable<SelectListItem> BuyerSelectList = _unitOfWork.Buyer.GetAll().Select(
c => new SelectListItem
{
Text = c.Buyer,
Value = c.Id.ToString()
});
IEnumerable<SelectListItem> ItemSelectList = _unitOfWork.Item.GetAll().Select(
c => new SelectListItem
{
Text = c.Item,
Value = c.Id.ToString()
});
ViewBag.BuyerSelectList = BuyerSelectList;
ViewBag.ItemSelectList = ItemSelectList;
return View(btbNewLien2);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(BTBNewLien2 obj)
{
if (ModelState.IsValid)
{
_unitOfWork.BTBNewLien2.Add(obj);
_unitOfWork.Save();
TempData["success"] = "Row Created Successfully!";
return RedirectToAction("Index");
}
return View(obj);
}
}
}
BTBNewLien2 create view:
#model CommercialCalculator.Models.BTBNewLien2
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>BTBNewLien2</h4>
<hr />
<div class="row ml-6">
<div class="col-md-4">
<form asp-action="Create">
<div class="form-group">
<label asp-for="BuyerSelectListId" class="control-label">Buyer</label>
<select asp-for="BuyerSelectListId" asp-items="ViewBag.BuyerSelectList" class="form-control">
<option disabled selected>--Select Buyer--</option>
</select>
</div>
<div class="form-group">
<label asp-for="ItemSelectListId" class="control-label">Item</label>
<select asp-for="ItemSelectListId" asp-items="ViewBag.ItemSelectList" class="form-control">
<option disabled selected>--Select Item--</option>
</select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
BTBNewLien2 index view:
#model IEnumerable<CommercialCalculator.Models.BTBNewLien2>
#{
ViewData["Title"] = "Index";
}
<table class="table table-bordered table-hover table-sm align-middle m-0" id="header">
<tr class="m-0" style="text-align:center;background-color: #17A2B8">
<th width="20%">
#Html.DisplayNameFor(model => model.BuyerSelectList)
</th>
<th>
#Html.DisplayNameFor(model => model.ItemSelectList)
</th>
</tr>
#foreach (var BTBNewLien2 in Model)
{
<tr class="m-0">
<td>
#Html.DisplayFor(modelItem => BTBNewLien2.BuyerSelectList)
</td>
<td>
#Html.DisplayFor(modelItem => BTBNewLien2.ItemSelectList)
</td>
</tr>
}
</table>
Try this way:
#Html.DropDownList("ItemSelectListId", new SelectList(ViewBag.ItemSelectListId, "Text", "Text"), "-- Select Item --", new { required = true, #class = "form-control" })
In my code, it works fine:
Controller:
[HttpGet]
public IActionResult Create()
{
List<SelectListItem> test = new()
{
new SelectListItem { Value = "1", Text = "test1" },
new SelectListItem { Value = "2", Text = "test2" },
new SelectListItem { Value = "3", Text = "test3" },
new SelectListItem { Value = "4", Text = "test4" }
};
ViewBag.ItemSelectListId = test;
return View();
}
[HttpPost]
public IActionResult Create(Test test)
{
return View();
}
View:
<div class="row ml-6">
<div class="col-md-4">
<form asp-action="Create">
<div class="form-group">
<label asp-for="ItemSelectListId" class="control-label">Buyer</label>
#Html.DropDownList("ItemSelectListId", new SelectList(ViewBag.ItemSelectListId, "Text", "Text"), "-- Select Item --", new { required = true, #class = "form-control" })
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
Test Result:

#Html.DisplayFor(ModelItem => item.Category.Name) doesn't show the Category Name

My project have 2 entity; Book - Category.
I want to show all Book's have a Category. But #Html.DisplayFor(ModelItem => item.Kategori.Ad) doesn't show the Category Name.
It should be shown on localhost but is doesn't show.
I added image about that.
Is there any solution for this?
My View Page.
{#using BenimKutuphanem.Areas.AdminPaneli.Models
#model IEnumerable<BenimKutuphanem.Entity.Kitap>
#{
ViewBag.Title = "Kitap Listesi";
}
<p>
#Html.ActionLink("Yeni Kitap Ekle", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Foto)
</th>
<th>
#Html.DisplayNameFor(model => model.Ad)
</th>
<th>
#Html.DisplayNameFor(model => model.Yazar)
</th>
<th>
#Html.DisplayNameFor(model => model.Kategori)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<img src="/#Html.DisplayFor(modelItem => item.Foto)" alt="Resim" width="250"/>
</td>
<td>
#Html.DisplayFor(modelItem => item.Ad)
</td>
<td>
#Html.DisplayFor(modelItem => item.Yazar)
</td>
<td>
#Html.DisplayFor(ModelItem => item.Kategori.Ad)
</td>
<td>
#Html.ActionLink("Düzenle", "Edit", new { id = item.Id }) |
#Html.ActionLink("Detaylar", "Details", new { id = item.Id }) |
#Html.ActionLink("Sil", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
}
controller
using BenimKutuphanem.Entity;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace BenimKutuphanem.Areas.AdminPaneli.Controllers
{
public class KitapController: Controller
{
private BenimKutuphanemEntities context = new BenimKutuphanemEntities();
// GET: AdminPaneli/Kitap/Index
public ActionResult Index()
{
var kitaplar = context.Kitap.ToList();
return View(kitaplar);
}
// GET: AdminPaneli/Kitap/Create
public ActionResult Create()
{
List<SelectListItem> degerler = (from i in context.Kategori.ToList()
select new SelectListItem
{
Text = i.Ad,
Value = i.Id.ToString()
}).ToList();
ViewBag.dgr = degerler;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Kitap kitap, HttpPostedFileBase Foto)
{
if (ModelState.IsValid)
{
if (Foto.ContentLength > 0)
{
var image = Path.GetFileName(Foto.FileName);
var path = Path.Combine(Server.MapPath("/Areas/AdminPaneli/Images/"), image);
Foto.SaveAs(path);
kitap.Foto = "Areas/AdminPaneli/Images/" + image;
try
{
context.Kitap.Add(kitap);
context.SaveChanges();
ViewBag.Bilgi = "Kitap veritabanına başarıyla kaydedildi.";
}
catch (Exception e)
{
ViewBag.Bilgi = "Kaydetme işlemi başarısız." + e.Message;
}
}
}
List<SelectListItem> degerler = (from i in context.Kategori.ToList()
select new SelectListItem
{
Text = i.Ad,
Value = i.Id.ToString()
}).ToList();
ViewBag.dgr = degerler;
return View();
}
// GET: AdminPaneli/Kitap/List
public ActionResult List()
{
var kitaplar = context.Kitap.ToList();
return View(kitaplar);
}
// GET: AdminPaneli/Kitap/Details
public ActionResult Details(int id)
{
var kitap = context.Kitap.Find(id);
return View(kitap);
}
// GET: AdminPaneli/Kitap/Edit
public ActionResult Edit(int id)
{
List<SelectListItem> degerler = (from i in context.Kategori.ToList()
select new SelectListItem
{
Text = i.Ad,
Value = i.Id.ToString()
}).ToList();
ViewBag.dgr = degerler;
var kitap = context.Kitap.Find(id);
return View(kitap);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, Kitap kitap)
{
List<SelectListItem> degerler = (from i in context.Kategori.ToList()
select new SelectListItem
{
Text = i.Ad,
Value = i.Id.ToString()
}).ToList();
ViewBag.dgr = degerler;
context.Entry(kitap).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("List");
}
// GET: AdminPaneli/Kitap/Delete
public ActionResult Delete(int id)
{
var kitap = context.Kitap.Find(id);
return View(kitap);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, Kitap kitap)
{
var _kitap = context.Kitap.Find(id);
context.Kitap.Remove(_kitap);
context.SaveChanges();
return RedirectToAction("List");
}
}
}
Output:
Fix this query
public ActionResult List()
{
var kitaplar = context.Kitap.Include(i=>i.Kategori).ToList();
return View(kitaplar);
}
If you have the same error somewhere else , fix the same way too.

ASP.NET MVC empty KeyValuePair into Controller

I have an Model like KeyValuePair<Book, List<Author>>, after saving changes to controller comes empty model. To Edit(int id) comes Id of Book.
To this method need to get KeyValuePair filled, but it comes empty. Help please.
[HttpPost]
public ActionResult Edit(KeyValuePair<Book, List<Author>> data)
Controller
public class HomeController : Controller
{
static ViewModelAuthorsBooks data = new ViewModelAuthorsBooks();
static Dictionary<Book, List<Author>> tempDict = new Dictionary<Book, List<Author>>();
public ActionResult Index()
{
data = new ViewModelAuthorsBooks();
data.dictionary = new Dictionary<Book, List<Author>>();
List<Author> temp = new List<Author>();
Book book1 = new Book
{
Id = 0,
Name = "Book1",
Genre = "Genre1",
Description = "DescriptionDescription",
Price = 22.42M
};
Author author = new Author
{
Id = 0,
Name = "Name1",
Surname = "Surname1",
SecondName = "Secondname1"
};
temp.Add(author);
Author author2 = new Author
{
Id = 1,
Name = "Name2",
Surname = "Surname2",
SecondName = "Secondname2"
};
temp.Add(author2);
data.dictionary.Add(book1, temp);
temp = new List<Author>();
Book book2 = new Book
{
Id = 1,
Name = "Book2",
Genre = "Genre2",
Description = "DescriptionDescription2",
Price = 44.44M
};
Author author3 = new Author
{
Id = 2,
Name = "Name3",
Surname = "Surname3",
SecondName = "Secondname3"
};
temp.Add(author3);
data.dictionary.Add(book2, temp);
tempDict = data.dictionary;
return View(data.dictionary);
}
public ActionResult Edit(int id)
{
var model = tempDict.FirstOrDefault(x => x.Key.Id == id);
return View(model);
}
[HttpPost]
public ActionResult Edit(KeyValuePair<Book, List<Author>> data)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
else
{
return View(data);
}
}
}
Classes
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Description { get; set; }
public string Genre { get; set; }
}
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string SecondName { get; set; }
}
public class ViewModelAuthorsBooks
{
public Dictionary<Book,List<Author>> dictionary { get; set; }
}
Views/Index
#using KeyValuePairTest.Models
#model IEnumerable<KeyValuePair<Book,List<Author>>>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="panel panel-default">
<div class="panel-heading">
Books List
</div>
<div class="panel-body">
<table class="table table-striped table-condensed table-bordered">
<tr>
<th class="text-center">
#Html.DisplayNameFor(x => x.Key.Id)
</th>
<th class="text-center">
#Html.DisplayNameFor(x => x.Key.Name)
</th>
<th class="text-center">
#Html.DisplayNameFor(x => x.Key.Genre)
</th>
<th class="text-right">
#Html.DisplayNameFor(x => x.Key.Price)
</th>
<th class="text-center">
Action
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td class="text-right">
#item.Key.Id
</td>
<td>
#Html.ActionLink(item.Key.Name, "Edit", new { item.Key.Id })
</td>
<td>
#Html.DisplayFor(modelItem => item.Key.Genre)
</td>
<td class="text-right">
#item.Key.Price.ToString("# USD")
</td>
<td class="text-center">
#using (Html.BeginForm("Delete", "Admin"))
{
#Html.Hidden("id", item.Key.Id)
<input type="submit" class="btn btn-default btn-xs" value="Remove" />
}
</td>
</tr>
}
</table>
</div>
<div class="panel-footer">
#Html.ActionLink("Add", "Create", null, new { #class = "btn btn-default" })
</div>
</div>
Views/Edit
#using KeyValuePairTest.Models
#model KeyValuePair<Book, List<Author>>
#{
ViewBag.Title = "Edit";
}
<div class="panel">
<div class="panel-heading">
<h5>Edit Book: #Model.Key.Name</h5>
</div>
#using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { app = #Model }))
{
<div class="panel-body">
#Html.HiddenFor(b => b.Key.Id)
<div class="form-group">
<label>Name:</label>
#Html.TextBoxFor(x => x.Key.Name, new { #class = "form-control" })
<input type="text" name="m" />
<label>Genre:</label>
#Html.TextBoxFor(x => x.Key.Genre, new { #class = "form-control" })
<label>Authors:</label>
#foreach (var author in Model.Value)
{
<label>Name</label>
#Html.TextBoxFor(x => author.Name);
<label>Surname</label>
#Html.TextBoxFor(x => author.Surname);
<label>Second name</label>
#Html.TextBoxFor(x => author.SecondName);
<p></p>
}
<label>Description:</label>
#Html.TextAreaFor(x => x.Key.Description, new { #class = "form-control", rows = 5 })
<label>Price:</label>
#Html.TextBoxFor(x => x.Key.Price, new { #class = "form-control" })
</div>
</div>
<div class="panel-footer">
<input type="submit" value="Save" class="btn btn-primary" />
#Html.ActionLink("Cancel", "Index", null, new { #class = "btn btn-default" })
</div>
}
</div>
Dictionary contains keys and values
In edit we see, that dictionary has values, they shown
Change value of Book name
Null
Thank's all for help, I find a solution
public class ViewModelUpdated
{
public Book book { set; get; }
public List<Author> lstAuthors { set; get; }
}
Just don't do a dictionary that's all :3

My form ignores Required attributes from model

I'm having troubles with my form validation. For some reason the form ignores any [Required] attribute I have in my model.
Model: (Stripped down for easy read)
public class NotEmployeesModel
{
public NotEmployeesModel()
{
DetailModel = new NotEmployeesDetailModel();
}
public NotEmployeesDetailModel DetailModel { get; set; }
}
public class NotEmployeesDetailModel
{
public NotEmployeesDetailModel()
{
}
public NotEmployeesDocumentModel DocumentModel { get; set; }
}
public class NotEmployeesDocumentModel
{
public NotEmployeesDocumentModel()
{
}
public NotEmployeeDocumentInputModel DocumentInput { get; set; }
public class NotEmployeeDocumentInputModel
{
public NotEmployeeDocumentInputModel()
{
}
public NotEmployeeDocumentInputModel(int notEmployeeId)
{
NotEmployeeId = notEmployeeId;
}
public int NotEmployeeId { get; set; }
public int SelectedDocumentType { get; set; }
[Required(ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName = "Star")]
public string Description { get; set; }
[Required(ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName = "Star")]
public HttpPostedFileBase File { get; set; }
}
}
For each view or partial I have a separate model class.
Form:
#model NotEmployeesDocumentModel
#using (Html.BeginForm("AddNotEmployeeDocument", "Home", FormMethod.Post, new { id = "form-add-document", enctype = "multipart/form-data" }))
{
#Html.HiddenFor(x => x.DocumentInput.NotEmployeeId)
<table class="table-output">
<thead>
<tr>
<td>#Html.Label("Sort", Labels.Sort)</td>
<td>#Html.Label("Description", Labels.Description)</td>
<td>#Html.Label("Type", Labels.Type)</td>
<td class="text-align-right"></td>
</tr>
</thead>
<tbody>
<tr>
<td>
<i class="fa fa-plus-square cursor-pointer add-document"></i>
<input type="file" id="DocumentInput_File" name="DocumentInput.File" required="required" />
#Html.ValidationMessageFor(x => x.DocumentInput.File)
</td>
<td>
#Html.TextBoxFor(x => x.DocumentInput.Description, new { #class = "width300px hardware-setup-input", placeholder = "Vul hier een omschrijving in..." })
#Html.ValidationMessageFor(x => x.DocumentInput.Description)
</td>
<td>
#Html.DropDownListFor(x => x.DocumentInput.SelectedDocumentType, Model.DocumentTypes, "--- Maak een keuze ---")
</td>
<td class="text-align-right">
<span id="btn-add-document" class="button-org">#Labels.Save</span>
</td>
</tr>
</tbody>
</table>
}
Structure of my page: View / Partial / Partial (Here is my form)
JS:
$("#btn-add-document").on("click", function () {
var frm = $("#form-add-document");
if (frm.valid()) {
frm.ajaxSubmit({
dataType: "html",
success: function (responseText) {
$("#document-container").html(responseText);
$("#DocumentInput_Description").text("");
$("#DocumentInput_SelectedDocumentType").val("");
loadDocumentPartial();
}
});
}
});
I'm using jQuery Form plugin from malsup to submit my form through ajax.
Controller:
[HttpPost]
public ActionResult AddNotEmployeeDocument(NotEmployeesDocumentModel input)
{
// do some code
}
As you can see in the parameters of my ActionResult I can't put NotEmployeesDocumentInputModel like I always do but I'm forced to use the parent class.
I have no idea what I'm doing wrong. This is the first time I encounter such problem.

Radio button list using editor templates for merging contacts

I am trying to display a form for merging two contacts in ASP.net MVC 5.
The form should look like this where each row holds a radio button group consisting of 2 options:
The form shows up just fine, and the radio groups work (I can select each group). However, when the model is posted back to the server, the Values list is empty (not preserved). I would like to get both the selected id but of course also the actual text value back in the controller. I prefer to do this using Editor Templates and if possible without for loops.
The current results (Values = null):
EDIT to respond to comments: I would prefer not to re-fetch the values in the controller again, because it results in a call to a web service. I have tried some variants of HiddenFor without results.
My models look like this:
public class Contact
{
public List<ContactRow> Rows { get; set; }
public Contact()
{
this.Rows = new List<ContactRow>();
this.Rows.Add(new ContactRow("First Name", "Homer", "Homie"));
this.Rows.Add(new ContactRow("Last Name", "Simpson", "Simson"));
this.Rows.Add(new ContactRow("Email", "mail1", "mail2"));
this.Rows.Add(new ContactRow("Company Phone", "Phone1", "Phone2"));
this.Rows.Add(new ContactRow("Mobile Phone", "Mobile1", "Mobile2"));
}
}
public class ContactRow
{
public int Selection { get; set; }
public string Label { get; set; }
public List<ValueSet> Values { get; set; }
public ContactRow(string Label, string LeftValue, string RightValue, int Selection = 0)
{
if (LeftValue== null) LeftValue= "";
if (RightValue== null) RightValue= "";
this.Label = Label;
this.Selection = Selection;
this.Values = new List<ValueSet>(2);
this.Values.Add(new ValueSet() { ID = 0, ValueText = LeftValue});
this.Values.Add(new ValueSet() { ID = 1, ValueText = RightValue});
}
public ContactRow() { }
}
public class ValueSet
{
public int ID { set; get; }
public string ValueText { set; get; }
}
The Controller:
public ActionResult Index()
{
Contact model = new Contact();
return View(model);
}
public ActionResult MergeContacts(Contact model)
{
return RedirectToAction("Index");
}
And the views:
Index.cshtml
#model RadioTest.Models.Contact
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm("MergeContacts", "Home", FormMethod.Post, new { encType = "multipart/form-data", id = "contactDetailsForm", name = "contactDetailsForm" }))
{
<div>
<table class="table" width="100%">
<tr>
<th style="text-align:left">Label</th>
#*<th style="text-align:right">R1</th>*#
<th style="text-align:left">
Left Value
</th>
#*<th style="text-align:right">R2</th>*#
<th style="text-align:left">
Right Value
</th>
</tr>
#Html.EditorFor(model => model.Rows)
</table>
<input type="submit" />
</div>
}
Editor Template for ContactRow:
ContactRow.cshtml
#model RadioTest.Models.ContactRow
<tr>
<td style="text-align:left">
#Html.DisplayFor(model => model.Label)
</td>
#foreach (var v in Model.Values)
{
<td style="text-align:left">
#Html.RadioButtonFor(model => model.Selection, v.ID) #v.ValueText
</td>
}
</tr>
#Html.HiddenFor(model => model.Label)
Just change your foreach to for:
#model MVCApp.Controllers.ContactRow
<tr>
<td style="text-align:left">
#Html.DisplayFor(model => model.Label)
</td>
#for (int i = 0; i < Model.Values.Count; i++)
{
<td style="text-align:left">
#Html.RadioButtonFor(model => model.Selection, Model.Values[i].ID) #Model.Values[i].ValueText
#Html.HiddenFor(model => Model.Values[i].ID)
#Html.HiddenFor(model => Model.Values[i].ValueText)
</td>
}
</tr>
#Html.HiddenFor(model => model.Label)

Resources