Using a list with MVC radiobuttonfor - asp.net-mvc-4

I am using radiobuttonfor in MVC 4 and I am trying to give the user a selection of items that he can select. My problem is when one of the items is selected and it's posted to the controller, the string value is a .net system.guid rather than the actual guid value.
#foreach (var person in Model.InterviewDates[i].Interviewers) // all interviewers - not filtered
{
var list = Model.InterviewDates[i].Interviewers.Select(p => p.InterviewerID).ToList();
#Html.Raw(person.InterviewerName + " ")
// TODO: Lambda for getting all Chairs based on interview type and interview date
#Html.RadioButtonFor(m => m.InterviewSchedules[i].Chair, list, new { #style = "width:auto;background:none;border:none" })
<br />
}
I have a list of people and it contains their user ids. I then want the user to select a radio button to bind that value to the model.
- list Count = 3 System.Collections.Generic.List<System.Guid>
+ [0] {5fb7097c-335c-4d07-b4fd-000004e2d221} System.Guid
+ [1] {5fb7097c-335c-4d07-b4fd-000004e2d222} System.Guid
+ [2] {5fb7097c-335c-4d07-b4fd-000004e2d223} System.Guid
+ Raw View
When I post it goes here:
[HttpPost]
public ActionResult SubmittedInterviews(InterviewManagement InterviewManagement)
{
return View();
}
This is what I can see in quick watch
- InterviewManagement {IMecheAdmin.Models.InterviewManagement} IMecheAdmin.Models.InterviewManagement
+ InterviewDates Count = 0 System.Collections.Generic.List<IMecheAdmin.Models.InterviewDate>
- InterviewSchedules Count = 1 System.Collections.Generic.List<IMecheAdmin.Models.InterviewSchedule>
- [0] {IMecheAdmin.Models.InterviewSchedule} IMecheAdmin.Models.InterviewSchedule
Chair "System.Collections.Generic.List`1[System.Guid]" string
Cofacilitator null string
Facilitator null string
+ InterviewDate {01/01/0001 00:00:00} System.DateTime
Location null string
Observer null string
Preference false bool
Site null string
+ Raw View
+ InterviewTypes Count = 0 System.Collections.Generic.List<IMecheAdmin.Models.InterviewType>
SelectedMembershipType null string
And this is not what I want:
Chair "System.Collections.Generic.List`1[System.Guid]" string
Doesn't say actual GUID. Any ideas?

Radio button is normally used where we want user to only select only one option from the provided item.
So, you need to pass single object instead of list:
foreach(var item in list)
{
#Html.RadioButtonFor(m => m.InterviewSchedules[i].Chair,
item.InterviewerID,
new { #style = "width:auto;background:none;border:none" })
}

Related

Using lambda expression to pass multiple values with aggregate functions to view in MVC (For nested tables)

I have to Tables named Tasks and TaskDetails, I'm currently working on a todo list web application using MVC 5.
I created a query to retrieve the rows from the two tables based on an employee ID as shown below
SELECT T.TaskID,T.Title,T.Status AS TaskStatus,T.EmpID,TD.SID,TD.ToDo,TD.EndDate,TD.EndTime,TD.Priority,TD.Status AS TDStatus
FROM TASKS T
INNER JOIN TaskDetails TD ON T.TaskID=TD.TaskID
WHERE T.EmpID='12345' ORDER BY SID DESC
In my Controller, I'm using the following code to pass the data to the View .
//Controller
public ActionResult MyToDoLists()
{
List<ToDoListsVM> todoLists = this.LoadPrivateData();
var booksGrouped = from b in todoLists
group b by new { b.TaskID,b.Title } into g
select new Group<int,string, ToDoListsVM> { Key = g.Key.TaskID,Title=g.Key.Title, Values = g };
ViewBag.ToDoLists = booksGrouped.ToList();
return View();
}
Lambda class
public class Group<K,K1, T>
{
public K Key;
public K1 Title;
public IEnumerable<T> Values;
}
In the view, the ToDos are grouped per each TaskID and TaskName, and the fields marked in green are retrieved based on the lambda expression as shown below
But my issue now, is that I cannot get the values for ToDos and Completed fields, as marked in RED.
Note:
ToDos shows the total of todo list per each task
Completed: shows the completed todos per each task

Using automapper.collection in aspnet core & ef core doesn't updated edited records in a collection

I'm using asnet boilerplaite aspnet core and ef core. I've initialized automapper.collection in PreInitialize as follows:
Configuration.Modules.AbpAutoMapper().Configurators.Add(
cfg =>{
cfg.AddCollectionMappers();
cfg.CreateMap<OrderDTO, Order>().EqualityComparison((odto, o) => odto.ID == o.ID);
cfg.CreateMap<OrderItemDTO, OrderItem>().EqualityComparison((odto, o) => odto.ID == o.ID);
}
);
I'm using ObjectMapper.Map(odto, o); to map between the dto and entity, but what I find are new orderitem in the orderitems collection within orders save fine, but any edits to existing entries seem to not update to the db.
The order entity and collection are loaded from the repository using the following:
var #item = await _orderRepository.GetAll().Include(x => x.Items).Include(x => x.Items).ThenInclude(x => x.Product).AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
here is the Update method:
public override async Task<OrderDto> Update(OrderDto input)
{
var ord = await _orderManager.GetA(input.Id);
ObjectMapper.Map(input, ord);
CheckErrors(await _orderManager.UpdateA(ord));
return MapToEntityDto(await _orderManager.GetA(input.Id));
}
The values of input and ord variables are as follows when trying to update the orderitem record:
input {OrderDto}
Code "1" string
Id 1 int
Items Count = 1 System.Collections.Generic.ICollection<OrderItemDto>
- [0] {OrderItemDto}
Id 1 int
OrderId 1 int
+ Product {ProductLoadDto}
ProductId 4 int
Quantity 22 double
MovementDate {28-Jul-18 2:36:41 AM} System.DateTime
ord {[Order 1]} Order
Code "1" string
Id 1 int
Items Count = 1 System.Collections.Generic.ICollection<OrderItem>
- [0] {OrderItem 1}
Id 1 int
OrderId 1 int
+ Product {[Product 4]} Venues.Products.Product
ProductId 4 int
Quantity 1 double
MovementDate {28-Jul-18 12:06:41 PM} System.DateTime
Is there something I'm missing to get automapper.collection to handle the collection edits automatically ?
Have you tried the Entity Framework Core repo?
https://github.com/AutoMapper/AutoMapper.Collection.EFCore/tree/development
I used the extension listed here to resolve the issue:
https://entityframeworkcore.com/knowledge-base/39452054/asp-net-core-with-ef-core---dto-collection-mapping

How to assign null/string to an int type in MVC Razor using Entity Framework?

I am using a simple MVC 4 application using Entity Framework.
In my View I am displaying data from of a table using webgrid.
View Also has Textboxes(EditorFor) for saving any new record in the table.
I am using partial view for the Textboxes, as in the beginning when the page is launched, the textboxes should remain empty.
Out of 5, two columns are of integer types.
In order to make the textboxes empty initially I am using a new object as -
#if (!dataGrid.HasSelection)
{
Datamodel = new EntityFrDemo.Models.FacultyDetails { DepartmentID = 0, Name = "", Subject = "", YrsExp = 0, Email = "" };
Html.RenderPartial("~/Views/Shared/_FacultyDetails.cshtml", Datamodel);
}
//------------------------------------------------------------------------
#Html.LabelFor(model => model.DepartmentID)
#Html.EditorFor(model => model.DepartmentID)
#Html.ValidationMessageFor(model => model.DepartmentID)
//-----------------------------------------------------------------------------
So I am able to make my boxes empty, however for the Integer type boxes '0' is coming, as I can only assign zero.
So How can I override/superimpose the integer value type boxes to empty string type so that boxes remains empty only in case when no row is selected i.e. in initial stage...?
When you use #Html.EditorFor() with a int value, Razor generate a html tag like this
<input type="number" name="propertyName" id="propertyName" value="propertyValue" />
If you didn't set a value for the int property, the default int value is zero. To set another value in the html tag, you can write it without Razor or you can set the value like the code below.
#Html.EditorFor(model => model.DepartmentID, new { htmlAttributes = new { #Value = "" } })
Note: It is capital "V", not a lower case "v".

Group By Sum Linq to SQL in C#

Really stuck with Linq to SQL grouping and summing, have searched everywhere but I don't understand enough to apply other solutions to my own.
I have a view in my database called view_ProjectTimeSummary, this has the following fields:
string_UserDescription
string_ProjectDescription
datetime_Date
double_Hours
I have a method which accepts a to and from date parameter and first creates this List<>:
List<view_UserTimeSummary> view_UserTimeSummaryToReturn =
(from linqtable_UserTimeSummaryView
in datacontext_UserTimeSummary.GetTable<view_UserTimeSummary>()
where linqtable_UserTimeSummaryView.datetime_Week <= datetime_To
&& linqtable_UserTimeSummaryView.datetime_Week >= datetime_From
select linqtable_UserTimeSummaryView).ToList<view_UserTimeSummary>();
Before returning the List (to be used as a datasource for a datagridview) I filter the string_UserDescription field using a parameter of the same name:
if (string_UserDescription != "")
{
view_UserTimeSummaryToReturn =
(from c in view_UserTimeSummaryToReturn
where c.string_UserDescription == string_UserDescription
select c).ToList<view_UserTimeSummary>();
}
return view_UserTimeSummaryToReturn;
How do I manipulate the resulting List<> to show the sum of the field double_Hours for that user and project between the to and from date parameters (and not separate entries for each date)?
e.g. a List<> with the following fields:
string_UserDescription
string_ProjectDescription
double_SumOfHoursBetweenToAndFromDate
Am I right that this would mean I would have to return a different type of List<> (since it has less fields than the view_UserTimeSummary)?
I have read that to get the sum it's something like 'group / by / into b' but don't understand how this syntax works from looking at other solutions... Can someone please help me?
Thanks
Steve
Start out by defining a class to hold the result:
public class GroupedRow
{
public string UserDescription {get;set;}
public string ProjectDescription {get;set;}
public double SumOfHoursBetweenToAndFromDate {get;set;}
}
Since you've already applied filtering, the only thing left to do is group.
List<GroupedRow> result =
(
from row in source
group row by new { row.UserDescription, row.ProjectDescription } into g
select new GroupedRow()
{
UserDescription = g.Key.UserDescription,
ProjectDescription = g.Key.ProjectDescription,
SumOfHoursBetweenToAndFromDate = g.Sum(x => x.Hours)
}
).ToList();
(or the other syntax)
List<GroupedRow> result = source
.GroupBy(row => new {row.UserDescription, row.ProjectDescription })
.Select(g => new GroupedRow()
{
UserDescription = g.Key.UserDescription,
ProjectDescription = g.Key.ProjectDescription,
SumOfHoursBetweenToAndFromDate = g.Sum(x => x.Hours)
})
.ToList();

SQL to Insert data into multiple tables from one POST in WebMatrix Razor Syntax

I've got two form fields from which the user submits a 'category' and an 'item'.
The following code inserts the category fine (I modified it from the WebMatrix intro PDF) but I've no idea how to then insert the 'item' into the Items table. I'll also need to add the Id of the new category to the new item row.
This is the code that's working so far
#{ var db = Database.OpenFile("StarterSite.sdf");
var Category = Request["Category"]; //was name
var Item = Request["Item"]; //was description
if (IsPost) {
// Read product name.
Category = Request["Category"];
if (Category.IsEmpty()) {
Validation.AddFieldError("Category", "Category is required");
}
// Read product description.
Item = Request["Item"];
if (Item.IsEmpty()) {
Validation.AddFieldError("Item",
"Item type is required.");
}
// Define the insert query. The values to assign to the
// columns in the Products table are defined as parameters
// with the VALUES keyword.
if(Validation.Success) {
var insertQuery = "INSERT INTO Category (CategoryName) " +
"VALUES (#0)";
db.Execute(insertQuery, Category);
// Display the page that lists products.
Response.Redirect(#Href("~/success"));
}
}
}
I'm guessing/hoping this is a very easy question to answer so hopefully there isn't much more detail required - but please let me know if there is. Thanks.
There's a Database.GetLastInsertId method within WebMatrix which returns the id of the last inserted record (assuming it's an IDENTITY column you are using). Use that:
db.Execute(insertQuery, Category);
var id = (int)db.GetLastInsertId(); //id is the new CategoryId
db.Execute(secondInsertQuery, param1, id);