How to save selected radio button value in MVC4 - asp.net-mvc-4

I am working in MVC4.In this I am using the following code for radio buttons :
Model :
public class PlatInspHistoryModels
{
public List<RadioButtonItem> RadioButtonList { get; set; }
public string SelectedRadioButton { get; set; }
}
public class RadioButtonItem
{
public string Name { get; set; }
public bool Selected { get; set; }
public string Value { get; set; }
public bool Visible { get; set; }
}
controller :
public ActionResult Index()
{
var viewModel = new PlatInspHistoryModels
{
RadioButtonList = new List<RadioButtonItem>
{
new RadioButtonItem
{
Name = "Topside", Value = "T",Selected = true,Visible = true
},
new RadioButtonItem
{
Name="Underwater", Value = "U",Selected = false,Visible = true
}
}
};
return View(viewModel);
}
View :
#using (Html.BeginForm("Index", "PlatInspHistory", FormMethod.Post, new { id = "form" }))
{
<table cellpadding="4" cellspacing="4">
<tr>
<td>
foreach (Cairs2.Models.RadioButtonItem item in Model.RadioButtonList)
{
#Html.DisplayFor(i => item.Name)
#Html.RadioButton("PlatInspHistoryModels.SelectedRadioButton", item.Value, item.Selected, new { #class = "formCheckbox", tabindex = "1" })
}
</td>
</tr>
</table>
}
Problem :
From the above code I am able to bind radio buttons as a list. But how I can get selected radio value on save event given below :
[HttpPost]
public ActionResult Index(PlatInspHistoryModels model)
{
}

Replace your foreach loop with this with a for loop and use strongly typed helpers:
for (var i = 0; i < Model.RadioButtonList.Count; i++)
{
#Html.DisplayFor(x => x.RadioButtonList[i].Name)
#Html.HiddenFor(x => x.RadioButtonList[i].Name)
#Html.RadioButtonFor(x => x.SelectedRadioButton, Model.RadioButtonList[i].Value, new { #class = "formCheckbox", tabindex = "1" })
}

I am working in MVC5, i have mcqs questions in the form of radio buttons that are randomly fetched from database here is my`[Table("Mcqs")]
public class MCQS
{ [Key]
public int Qid { get; set; }
[Required(ErrorMessage = "Please Enter Skill.")]
public string Skill { get; set; }
[Required(ErrorMessage = "Please Enter Question.")]
public string Question { get; set; }
[Required(ErrorMessage = "Please Enter Level.")]
public string Levels { get; set; }
[Required(ErrorMessage = "Please Enter Options.")]
public string AnsOpt1 { get; set; }
[Required(ErrorMessage = "Please Enter Options.")]
public string AnsOpt2 { get; set; }
[Required(ErrorMessage = "Please Enter Options.")]
public string AnsOpt3 { get; set; }
[Required(ErrorMessage = "Please Enter Options.")]
public string AnsOpt4 { get; set; }
[Required(ErrorMessage = "Please Set Weightage.")]
and controller
public ActionResult Index()
{ return View((from a in ne.Mcqs orderby Guid.NewGuid() select a).Take(2).ToList()); }
and view
#foreach (var item in Model)
{<tr>
<td>
#Html.DisplayFor(modelItem=>item.Qid)</td>
<td> #Html.DisplayFor(modelItem => item.Question)</td> <td>
#Html.RadioButton("skillsq1", new { id = "1"}).
#Html.DisplayFor(modelItem => item.AnsOpt1)</td><td>
#Html.RadioButton("skillsq1", new { id = "2"})
#Html.DisplayFor(modelItem => item.AnsOpt2) </td><td>
#Html.RadioButton("skillsq1", new { id = "3" })
#Html.DisplayFor(modelItem => item.AnsOpt3) </td> <td>
#Html.RadioButton("skillsq1", new { id = "4" })
#Html.DisplayFor(modelItem => item.AnsOpt4) </td> </tr>}
i want to ask that how i get the value of the checked radio button of the shuffled question

Related

Asp Core Filter & Search Data Using Drop Downs & Search Bars

I would like users to search through pets using a search bar or drop down lists. I tried using viewbag and asp tag helpers but I keep getting errors. Below is a picture of what i'm going for. Any help is appreciated.
Model
public class Reptile
{
public int ReptileId { get; set; }
public string Name { get; set; }
public string Age { get; set; }
[Display(Name ="Reptile's Image")]
public byte[] Image { get; set; }
[Display(Name ="Food Requirements")]
public string FoodReq { get; set; }
[Display(Name="Habitat Requiremtns")]
public string HabitatReq { get; set; }
public string Gender { get; set; }
public string Type { get; set; }
public string Size { get; set; }
public string Color { get; set; }
[Display(Name="Recent Checkup")]
public bool RecentCheckup { get; set; }
public bool Trained { get; set; }
public bool Neutered { get; set; }
public bool Declawed { get; set; }
[Display(Name = "Good With Other Reptiles")]
public bool GoodWithRept { get; set; }
[Display(Name = "Good With Kids")]
public bool GoodWithKids { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public int ApplicationUserId { get; set; }
}
Controller
public async Task<IActionResult> Index(string searchString)
{
var reptiles = from r in _context.Reptiles
select r;
if (!string.IsNullOrEmpty(searchString))
{
reptiles = reptiles.Where(r => r.Type.Contains(searchString));
}
return View(await reptiles.ToListAsync());
}
View
<form asp-controller="Reptiles" asp-action="Index" method="get">
<div class="form-actions no-color">
<p>
Search By Type: <input type="text" name="SearchString" />
<input type="submit" value="Filter" class="btn btn-default" /> |
<a asp-action="Index">Back to Full List</a>
</p>
</div>
</form>
I've been trying to follow the docs here Tutorial: Add sorting, filtering, and paging - ASP.NET MVC with EF Core. Not having any luck though.
Here is a simple demo to show how to use searchstring:
Controller:
public IActionResult Index(string searchString)
{
IEnumerable<Reptile> list = new List<Reptile> { new Reptile { Type = "t1", Name= "Reptile1" }, new Reptile { Type = "t2", Name = "Reptile2" }, new Reptile { Type = "t3", Name = "Reptile3" } };
ViewData["CurrentFilter"] = searchString;
if (!String.IsNullOrEmpty(searchString))
{
list = list.Where(s => s.Name.Contains(searchString));
}
return View(list);
}
View:
Find by name:
|
Back to Full List
<table>
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Type)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<input type="text" asp-for="#item.Type">
</td>
</tr>
}
</tbody>
</table>
result:
Okay, I figured out how to use select to filter the reptile page by using the data users already added to the database from the properties in the model. I had to create a view model and add the Reptile model to it.
View Model
public class ReptileGenderViewModel
{
public Reptile Reptile { get; set; }
public List<Reptile> reptiles;
public SelectList genders;
public string reptileGender { get; set; }
}
Reptile Controller
public async Task<IActionResult> Index(string searchString, string reptileGender)
{
IQueryable<string> genderQuery = from g in _context.Reptiles
orderby g.Gender
select g.Gender;
var reptiles = from r in _context.Reptiles
select r;
if (!string.IsNullOrEmpty(searchString))
{
reptiles = reptiles.Where(r => r.Type.Contains(searchString));
}
if (!string.IsNullOrEmpty(reptileGender))
{
reptiles = reptiles.Where(g => g.Gender == reptileGender);
}
var reptileGenderVM = new ReptileGenderViewModel();
reptileGenderVM.genders = new SelectList(await genderQuery.Distinct().ToListAsync());
reptileGenderVM.reptiles = await reptiles.ToListAsync();
return View(reptileGenderVM);
}
View
<select asp-for="reptileGender" asp-items="Model.genders">
<option value="">All</option>
</select>

How to deal with this decimal error for a price?

I'm working on this app that should show on "localhost/catalog" some data. I have a library for the models and for the services that the application might use. I am getting this error:
InvalidOperationException: The property 'Price' is not a navigation
property of entity type 'StoreAsset'. The 'Include(string)' method can
only be used with a '.' separated list of navigation property names.Microsoft.EntityFrameworkCore.Query.Internal.IncludeCompiler.WalkNavigations(IEntityType entityType, IReadOnlyList<string> navigationPropertyPaths, IncludeLoadTree includeLoadTree, bool shouldThrow)
Here is the code that I'm using (controller, models and view) and the service methods on bottom:
public class CatalogController : Controller
{
private IStoreAsset _assets;
public CatalogController(IStoreAsset assets)
{
_assets = assets;
}
public ActionResult Index()
{
var assetModels = _assets.GetAll();
var listingResult = assetModels
.Select(result => new AssetIndexListingModel
{
Id = result.Id,
Tipology = _assets.GetTipology(result.Id),
Size = _assets.GetSize(result.Id),
Price = decimal.Parse(_assets.GetPrice(result.Id))
});
var model = new AssetIndexModel()
{
Assets = listingResult
};
return View(model);
}
public class AssetIndexListingModel
{
public int Id { get; set; }
public string Size { get; set; }
public decimal Price { get; set; }
public string Tipology { get; set; }
public string ImageUrl { get; set; }
}
public abstract class StoreAsset
{
public int Id { get; set; }
[Required]
public Status Status { get; set; }
[Required]
public decimal Price { get; set; }
public string ImageUrl { get; set; }
}
public class Dress : StoreAsset
{
[Required]
public string Color { get; set; }
[Required]
public string Tipology { get; set; }
[Required]
public string Size { get; set; }
}
#model Models.Catalog.AssetIndexModel
<div id="assets">
<h3></h3>
<div id="assetsTable">
<table class="table table-condensed" id="catalogIndexTable">
<thead>
<tr>
<th>Size</th>
<th>Price</th>
<th>Tipology</th>
</tr>
</thead>
<tbody>
#foreach (var asset in Model.Assets)
{
<tr class="assetRow">
<td class="">
<a asp-controller="Catalog" asp-action="Detail" asp-route-id="#asset.Id">
<img src="#asset.ImageUrl" class="imageCell" />
</a>
</td>
<td class="">#asset.Price</td>
<td class="">#asset.Size</td>
<td class="">#asset.Tipology</td>
</tr>
}
</tbody>
</table>
</div>
public class StoreAssetService : IStoreAsset
{
private Context _context;
public StoreAssetService(Context context)
{
_context = context;
}
public void Add(StoreAsset newAsset)
{
_context.Add(newAsset);
_context.SaveChanges();
}
public IEnumerable<StoreAsset> GetAll()
{
return _context.StoreAssets
.Include(asset => asset.Status)
.Include(asset => asset.Price);
}
public StoreAsset GetById(int id)
{
// Return a query (same as returning GetAll().FirstOrDefault(...))
return _context.StoreAssets
.Include(assets => assets.Status)
.Include(assets => assets.Price)
// So it can return null with no problem
.FirstOrDefault(asset => asset.Id == id);
}
public StoreBranch GetCurrentLocation(int id)
{
throw new NotImplementedException();
}
// To implement and test
public string GetPrice(int id)
{
return _context.Dresses.FirstOrDefault(p => p.Id == id).Price.ToString();
}
public string GetSize(int id)
{
return _context.Dresses.FirstOrDefault(s => s.Id == id).Size;
}
public string GetStatus(int id)
{
throw new NotImplementedException();
}
public string GetTipology(int id)
{
var dress = _context.StoreAssets.OfType<Dress>()
.Where(b => b.Id == id);
// For now return other if it's not a party dress
return dress.Any() ? "Party" : "Other";
}
}
Should I use some ForeignKey attribute or change Price to a string?
Any help would be great thanks
As pointed out in the error message, the Include is for the Navigation property only.
You need to change below:
return _context.StoreAssets
.Include(asset => asset.Status)
.Include(asset => asset.Price);
To:
return _context.StoreAssets
.Include(asset => asset.Status).ToList();
Reference: https://learn.microsoft.com/en-us/ef/core/modeling/relationships#definition-of-terms
https://learn.microsoft.com/en-us/ef/core/querying/related-data
I am having yet another problem. When I go to "localhost/catalog" the page should display all columns/entries that I have in the database but it only displays one column. Is there something wrong in the foreach cicle?

Creating HTML table using Asp.net MVC Model

I am trying to create a dynamic table using MVC Model. This is my Model.
public class PrescriptionEditModel
{
[Required]
public Guid Id { get; set; }
[Required]
[Display(Name = "Medicine List")]
public List<PrescriptionMedicineModel> PrescriptionList { get; set; }
}
public class PrescriptionMedicineModel
{
[Required]
public Guid Id { get; set; }
[Required]
[Display(Name = "Medicine")]
public Guid MedicineId { get; set; }
[Required]
[Display(Name = "Prescription Duration")]
public Guid PrescriptionDurationId { get; set; }
public string NumberOf { get; set; }
}
And My Controller code is
public ActionResult Create()
{
ViewBag.PatientId = new SelectList(db.Patients.Where(h => h.HospitalId == hp.HospitalId), "Id", "FirstName");
ViewBag.MedicineId = new SelectList(db.Medicines.Where(h => h.HospitalId == hp.HospitalId), "Id", "Name");
ViewBag.PrescriptionFrequencyId = new SelectList(db.PrescriptionFrequencies.Where(h => h.HospitalId == hp.HospitalId), "Id", "Name");
PrescriptionMedicineModel prescription = new PrescriptionMedicineModel()
{
MedicineId = Guid.Empty,
PrescriptionDurationId = Guid.Empty,
PrescriptionFrequencyId = Guid.Empty,
PrescriptionWhentoTakeId = Guid.Empty
};
List<PrescriptionMedicineModel> newPrescriptionList = new List<PrescriptionMedicineModel>();
newPrescriptionList.Add(prescription);
PrescriptionEditModel newModel = new PrescriptionEditModel()
{
CaseHistory = null,
DoctorName =null,
HospitalId = hp.HospitalId,
PatientId = Guid.Empty,
PrescriptionDate = null,
PrescriptionList = newPrescriptionList
};
return View(newModel);
}
And My View is
<table class="table table-hover">
<thead>
<tr>
<th>Medicine Name</th>
<th>Duration</th>
</tr>
</thead>
<tbody>
#for (var i = 0; i < Model.PrescriptionList.Count; i++)
{
<tr>
<td>#Html.DropDownListFor(m => Model.PrescriptionList[i].MedicineId, new SelectList(ViewBag.MedicineId, "Id", "Name"))</td>
<td>#Html.DropDownListFor(m => Model.PrescriptionList[i].PrescriptionDurationId, new SelectList(ViewBag.PrescriptionFrequencyId, "Id", "Name"))</td>
</tr>
}
</tbody>
This is giving an error saying "DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'Id'.]".
I am trying to create list of medicine with list of items to allow the users edit the details of the medicine. User has to be given the ability to edit the items.
The DropDownListFor is not binding the items to the dropdown.
Any thoughts
Here is an example, I believe your Id and Name fields don't match the model, see how my model has these two properties:
View:
#model XYZ.Models.Adviser
<div class="form-">
<label asp-for="PracticeId" class="control-label">Practice</label>
#Html.DropDownList("PracticeId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.PracticeId)
</div>
Controller:
private void PopulatePracticesDropDownList(object selectedPractice = null)
{
var practicesQuery = from d in _context.Practice
.GroupBy(a => a.Name)
.Select(grp => grp.First())
orderby d.Name
select d;
ViewBag.PracticeId = new SelectList(practicesQuery, "ID", "Name", selectedPractice);
}
Model, it has properties ID and Name:
public class Practice
{
public int ID { get; set; }
[Required]
[Display(Name = "Practice Name")]
public string Name { get; set; }
}
public class Adviser
{
public int ID { get; set; }
[Required]
[Display(Name = "Adviser Name")]
public string Name { get; set; }
[Required]
public int PracticeId { get; set; }
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public string Practice { get; set; }
}

search function in ASP.NET MVC not working properly

i have a student table in my database that i created and i have a view that displays a list of all the students grouped by class... on top of the view i made a textbox and a search button to be able to access the student information faster. The problem is that i when i enter the first name and the last name in the textbox, nothing comes up. When i enter only the first name or only the last name, then it finds it. I'm new to programming and i can't figure out how to make it work. I would really appreciate if someone can help me with this. This is part of my code:
[HttpGet]
public ActionResult ViewStudents()
{
ViewBag.classes = db.Courses.ToList();
var studentCourses = db.StudentCourses.OrderBy(s=>s.Person.FirstName).ToList();
return View(studentCourses);
}
[HttpPost]
public ActionResult ViewStudents(string SearchString)
{
var student=new List<int>();
List<StudentCourse>sc=new List<StudentCourse>();
ViewBag.classes = db.Courses.ToList();
var studentCourse=db.StudentCourses.ToList();
var studentCourses = db.StudentCourses.OrderBy(s => s.Person.FirstName).ToList();
var substring = SearchString.IndexOf(" ").ToString();
if (!string.IsNullOrEmpty(SearchString))
{
student = (from p in db.People
where (p.FirstName.Contains(SearchString)) && (p.LastName.Contains(substring))||((p.FirstName.Contains(SearchString)) || (p.LastName.Contains(SearchString)))
select p.PersonId).ToList();
}
foreach (var s in studentCourse)
{
foreach (var i in student)
{
if (s.StudentId == i)
{
sc.Add(s);
}
}
}
return View(sc);
}
This is my view:
#model List<SchoolFinalProject.Models.StudentCourse>
#using (Html.BeginForm())
{
<div style="font-size:16px;"> <input type="text" id="search" placeholder="search" Name="SearchString" /><span class="glyphicon glyphicon-search"></span>
<input type="submit" value="search"></div>
}
#{
List<int> c = new List<int>();
foreach (var courses in ViewBag.classes)
{
foreach(var s in Model)
{
if(courses.CourseId==s.CourseId)
{
c.Add(courses.CourseId);
}
}
}
}
#foreach (var course in ViewBag.classes)
{
if(c.Contains(course.CourseId))
{
<h2>#course.Name<span>-</span>#course.Gender</h2>
<table class="table table-hover table-bordered table-striped">
<tr><th>First Name</th><th>Last Name</th><th>Email</th><th>Phone Number</th><th>Address</th><th>Date Of Birth</th></tr>
#foreach (var s in Model)
{
if(course.CourseId==s.CourseId)
{
<tr>
<td>#s.Person1.FirstName</td>
<td>#s.Person1.LastName</td>
<td>#s.Person1.Email</td>
<td>#s.Person1.PhoneNumber</td>
<td>#s.Person1.Address</td>
<td>#s.Person1.DateOfBirth</td>
<td>
<span class="glyphicon glyphicon-edit"></span>
#Html.ActionLink("Edit", "Edit","Person", new { id = s.Person1.PersonId }, null) |
<span class="glyphicon glyphicon-trash"></span>
#Html.ActionLink("Details", "Details","Person", new { id = s.Person1.PersonId }, null)
</td>
</tr>
}
}
</table>
}
}
Go to top of page
this is my person Model:
public partial class Person
{
public Person()
{
this.Bonus = new HashSet<Bonu>();
this.ConversationHistories = new HashSet<ConversationHistory>();
this.ConversationHistories1 = new HashSet<ConversationHistory>();
this.EmployeePaymentDetails = new HashSet<EmployeePaymentDetail>();
this.StudentCourses = new HashSet<StudentCourse>();
this.StudentCourses1 = new HashSet<StudentCourse>();
this.TeacherCourses = new HashSet<TeacherCourse>();
this.Reminders = new HashSet<Reminder>();
}
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
public Nullable<System.DateTime> DateOfBirth { get; set; }
public PersonType PersonTypeId { get; set; }
public Nullable<System.DateTime> LastModified { get; set; }
public Nullable<int> Gender { get; set; }
public Nullable<int> Status { get; set; }
public string FullName
{
get { return FirstName + ", " + LastName; }
}
public virtual ICollection<Bonu> Bonus { get; set; }
public virtual ICollection<ConversationHistory> ConversationHistories { get; set; }
public virtual ICollection<ConversationHistory> ConversationHistories1 { get; set; }
public virtual ICollection<EmployeePaymentDetail> EmployeePaymentDetails { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
public virtual ICollection<StudentCourse> StudentCourses1 { get; set; }
public virtual ICollection<TeacherCourse> TeacherCourses { get; set; }
public virtual ICollection<Reminder> Reminders { get; set; }
}
}
You might want to try concatenating the first and last name properties in your person model like this:
[Display(Name = "Full Name")]
public string FullName
{
get
{
return LastName + ", " + FirstMidName;
}
}
There is a very good tutorial on what you are trying to do here: https://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application
Also see this page of same tutorial: https://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
As an aside, you might want to check out using the Datatables plugin, which gives you search functionality without have to query your database with each search: https://datatables.net

Model properties are null after submit

I have this model:
public partial class Group
{
public Group()
{
this.ParameterGroup = new HashSet<ParameterGroup>();
}
public string GroupId { get; set; }
public string Responsibility { get; set; }
public virtual Text GroupDescText { get; set; }
public virtual Text GroupNameText { get; set; }
public virtual ICollection<ParameterGroup> ParameterGroup { get; set; }
}
public partial class Text
{
public Text()
{
this.ParamName = new HashSet<Parameter>();
this.ParamDesc = new HashSet<Parameter>();
this.EnumElemName = new HashSet<EnumElem>();
this.IoDeviceInfoText = new HashSet<IoDeviceInfo>();
this.IoCatText = new HashSet<IoDeviceInfo>();
this.GroupDesc = new HashSet<Group>();
this.GroupName = new HashSet<Group>();
this.Type = new HashSet<Type>();
this.ParamDispPath = new HashSet<Parameter>();
this.EnumElemText = new HashSet<EnumElem>();
this.TextValue = new HashSet<TextValue>();
}
public string TextId { get; set; }
public string XmlId { get; set; }
public virtual ICollection<Parameter> ParamName { get; set; }
public virtual ICollection<Parameter> ParamDesc { get; set; }
public virtual ICollection<EnumElem> EnumElemName { get; set; }
public virtual ICollection<IoDeviceInfo> IoDeviceInfoText { get; set; }
public virtual ICollection<IoDeviceInfo> IoCatText { get; set; }
public virtual ICollection<Group> GroupDesc { get; set; }
public virtual ICollection<Group> GroupName { get; set; }
public virtual ICollection<Type> Type { get; set; }
public virtual ICollection<Parameter> ParamDispPath { get; set; }
public virtual ICollection<EnumElem> EnumElemText { get; set; }
public virtual ICollection<TextValue> TextValue { get; set; }
}
This is my Controller:
public class GroupController : Controller
{
// GET: Group
public ActionResult Index()
{
return PartialView("Index", GroupModel.Instance.getGroups());
}
public ActionResult Edit(string id)
{
Group group = KebaContext.SessionBasedContext().GroupSet.Where(g => g.GroupId == id).FirstOrDefault();
List<Language> langs = KebaContext.SessionBasedContext().LanguageSet.ToList();
foreach(Language l in langs)
{
if(group.GroupDescText == null)
{
group.GroupDescText = new Text();
TextValue value = new TextValue();
value.TextId = Guid.NewGuid().ToString("N");
value.LangId = l.LangId;
value.Value = "";
group.GroupDescText.TextValue.Add(value);
}
if (group.GroupNameText == null)
{
group.GroupNameText = new Text();
TextValue value = new TextValue();
value.TextId = Guid.NewGuid().ToString("N");
value.LangId = l.LangId;
value.Value = "";
group.GroupNameText.TextValue.Add(value);
}
if (group.GroupDescText != null && group.GroupDescText.TextValue.Where(x => x.LangId == l.LangId).FirstOrDefault() == null) //just one lang is available
{
TextValue value = new TextValue();
value.TextId = group.GroupDescText.TextValue.First().TextId;
value.LangId = l.LangId;
value.Value = "";
group.GroupDescText.TextValue.Add(value);
}
if (group.GroupNameText != null && group.GroupNameText.TextValue.Where(x => x.LangId == l.LangId).FirstOrDefault() == null) //just one lang is available
{
TextValue value = new TextValue();
value.TextId = group.GroupNameText.TextValue.First().TextId;
value.LangId = l.LangId;
value.Value = "";
group.GroupNameText.TextValue.Add(value);
}
}
return View(group);
}
[HttpPost]
public ActionResult Edit(Group xyz)
{
return RedirectToAction("Index", "Types");
}
}
This is my View:
#using System.Web.Mvc.Html;
#model Keba.Data.EF.Group
#{
ViewBag.Title = "Group Editing";
}
<h2>Edit Group</h2>
<div id="groupEdit">
#using (Html.BeginForm("Edit", "Group", FormMethod.Post))
{
#Html.HiddenFor(model => model.GroupId);
<table class="userEditAddTable">
<tr><th>Responsibility</th><td>#Html.EditorFor(model => model.Responsibility)</td></tr>
#foreach (var name in Model.GroupNameText.TextValue)
{
#Html.HiddenFor(model => name.LangId)
#Html.HiddenFor(model => name.Value)
<tr><th>GroupNameText(#Html.DisplayFor(model => name.LangId))</th><td> #Html.TextBoxFor(model => name.Value)</td></tr>;
}
#foreach (var desc in Model.GroupDescText.TextValue)
{
#Html.HiddenFor(model => desc.LangId)
#Html.HiddenFor(model => desc.Value)
<tr><th>GroupDescText(#Html.DisplayFor(model => desc.LangId))</th><td> #Html.TextBoxFor(model => desc.Value)</td></tr>;
}
</table>
<br />
<div id="buttons">
<input name="Save" type="submit" value="Save" class="button" />
<input name="Cancel" type="submit" value="Cancel" class="button" />
</div>
}
</div>
Problem:
If I try to change the value of a Text in the group model e.g. GroupNameText.TextValue.Value send it to the controller (submit). The properties GroupNameText and GroupDescText are null.
I have also tried the solution with propertybinding ([Bind(Include = "GroupDescText,GroupNameText")] Group xyz) which also doesn't work
First, remember that only properties that are posted (i.e. have a form input element representing them) will be populated.
Second, the names of the input elements must match up to what the model binder expects on post, or it will discard the values, as it won't know what to do with them. In particular, with enumerables, this means you need to use for loops rather than foreach, so that Razor can create the right name binding:
#for (var i = 0; i < Model.GroupNameText.TextValue; i++)
{
#Html.HiddenFor(m => m.GroupNameText.TextValue[i].LangId)
#Html.HiddenFor(m => m.GroupNameText.TextValue[i].Value)
...
}
That will result in a name attribute like GroupNameText.TextValue[0].LangId, which the model binder should be able to bind appropriately, whereas your field names are currently just LangId, which is meaningless on post.
Have a look at this similar to your approach is to have a list in the view, you might need to have partials.