mvc select second table data using linq - asp.net

/*
hallo, I am new in mvc and linq. I've 2 table in relation many to many: 1)employe 2)device
Selecting an employe I'd like to see his devices:
-Marco
-Franco
Selecting Marco should appear the devices associated to him.
My code (not work):
Controller:
*/
public ActionResult VediDevice(int id)
{
Impiegato impi = new Impiegato();
List<Device> ListDevice = new List<Device>();
using (DatabaseMVCCOntrolsEntities db = new DatabaseMVCCOntrolsEntities())
{
ListDevice= db.Devices.Where(u => db.ImpiegatiDevice.Any(m => m.impiegatiID == id)).ToList(); <---???
}
return View(ListDevice);
}
VediDevice.cshtml:
#model List<MVCControlToolkit.Models.Device>
#{
ViewBag.Title = "VediDevice";
}
<h2>VediDevice</h2>
<table class="table table-striped table-condensed">
<tr>
<th>
NOME
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.nome)
</td>
</tr>
}
</table>
Not work.
What should I do?
Thank you
Ale

Use Include before where
ListDevice= db.Devices.ToList().Where(u => u.item.Any(m => m.impiegatiID == id)).ToList();
and add your Device class
List<ImpiegatiDevice> item{get;set;}

Related

asp.net event handler for table click is called twice

I have a table with some column in a asp.net mvc core project.
My view file looks like this
<h1>Items</h1>
<div class="panel-body">
<table class="table table-bordered table-responsive table-hover">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Rating</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Items)
{
<tr onclick="location.href='#(Url.Action("ShowItemDetails", "Item", new {Id = item.FilmId}))'">
<td>#item.Id</td>
<td>#item.Title</td>
<td>#item.Rating</td>
<td>#Html.ActionLink("Edit", "Edit", "Show", new { id = item.Id }) | #Html.ActionLink("Rate this", "RateItem", new { id = item.Id }) </td>
</tr>
}
</tbody>
</table>
</div>
The problem is that when i click on a row, the controller method ShowItemDetails is called twice(!).
I can not see from the code above why this happens. Also, clicking on Edit or Rate this calls first ShowItemDetails and then immediately Edit or RateItem method in controller. Any suggestion how this can be solved?
Clicking on Edit or Rate this calls first ShowItemDetails and then immediately Edit or RateItem method because Edit is under a table row and on tablerow, you have called showitemdetails action.so, when you click on td , it gets first executed row action then td action.that's why it get called twice.
I hope, you want to show details and edit options with data of table and Edit is controller name.
Tweak your table code like below:
<tbody>
#foreach (var item in Model.Items)
{
<tr>
<td>#Html.ActionLink("Show Details","ShowItemDetails","Item",new {Id = item.FilmId})</td>
<td>#item.Id</td>
<td>#item.Title</td>
<td>#item.Rating</td>
<td>#Html.ActionLink("Edit", "Edit", "Show", new { id = item.Id }) | #Html.ActionLink("Rate this", "RateItem", new { id = item.Id }) </td>
</tr>
}
</tbody>
The problem seems to be caused be something i thought was irrelevant
having a null image cause the method to be called twice. Setting it to
solves this.
Need to add code to check for Model.Image != null
Very strange!!

Generate links using values from the model

I have the following Mvc 4 razor code
#foreach (var item in Model.DealDetails) {
<tr>
<td>#Html.DisplayFor(m => item.DetailId)</td>
<td>#Html.DisplayFor(m => item.AppGuid)</td>
....
</tr>
I want to generate a link in another <td> column for each row. The link will look like
<a href="/Control/Action/{item.DetailId}?h={item.AppGuid}">
Link text
</a>
The control and action are in the same project. Is there any help function to do it? I want the link not to be created when item.AppGuid is null.
#foreach (var item in Model.DealDetails) {
<tr>
<td>#Html.DisplayFor(m => item.DetailId)</td>
<td>#Html.DisplayFor(m => item.AppGuid)</td>
#if(item.AppGuid != null){
<td>#Html.ActionLink("text", "action", "controller", new { id = item.DetailId , h = item.AppGuid}, null)</td>
}
</tr>

Persisting session data to child views MVC 3

So I'm working on an MVC 3 project that pulls from multiple (10) tables from a legacy data source to a Master View with 6 partials. There is one table that has data on every child view, so we decided to store that in session data and then populate the rest of the child views with whatever other data is needed.
When we originally tried to do this, we were getting null reference exceptions to the session data. I've come up with a solution, but it seems very clunky and I don't think it's best practices/introducing unnecessary state.
Relevant code to follow:
This is what we have on the main controller:
public ActionResult PolicyView(string PolicyID)
{
IPolicyHolder phdata = new PolicyHolderData();
Polmast policy = phdata.GetPolicyFromUV(PolicyID);
ViewBag.FullName = policy.FULLNAME;
ViewBag.PolicyID = PolicyID;
Session["polmast"] = policy;
return View("PolicyView");
}
And then in our main view, one of the links to the partial child views:
<div id="Billing">
#{ Html.RenderAction("Billing", Session["polmast"] ); }
</div>
In the child controller:
public ActionResult Billing(object sessiondata)
{
return PartialView("_Billing", sessiondata);
}
And in the child view:
#{var polmast = (Polmast)Session["polmast"];}
**snip**
<table id="premiumsgrid" class="display" border="1"
cellpadding="0" cellspacing="0" width="50%">
<thead>
<tr>
<th>Annual</th>
<th>Semi-Annual</th>
<th>Quarterly</th>
<th>Monthly</th>
</tr>
</thead>
<tbody>
<tr>
<td>#polmast.PAN</td>
<td>#polmast.PSA</td>
<td>#polmast.PQT</td>
<td>#polmast.PMO</td>
</tr>
</tbody>
</table>
I would recommend starting to use models and returning those to your views instead of passing around the session object and casting it within your view. It would make this code much more clean.
This is how I would structure my code:
public ActionResult PolicyView(string PolicyID)
{
IPolicyHolder phdata = new PolicyHolderData();
Polmast policy = phdata.GetPolicyFromUV(PolicyID);
PolicyModel model = new PoliceModel() {
FullName = policy.FULLNAME,
PolicyID = PolicyID
//Populate other properties here.
};
Session["polmast"] = policy;
return View("PolicyView", model);
}
Then I would set up your main view (there's no need to wrap this call in curly braces and you shouldn't need to pass any route values):
<div id="Billing">
#Html.RenderAction("Billing")
</div>
The child controller:
public ActionResult Billing()
{
//Get the data out of session; it should already exist since your parent controller took care of it.
var policyData = (Polmast)Session["polmast"];
PolicyModel model = new PoliceModel() {
FullName = policy.FULLNAME,
PolicyID = PolicyID
//Populate other properties here.
};
return PartialView("_Billing", model);
}
And your child view:
#model Polmast
snip
<table id="premiumsgrid" class="display" border="1"
cellpadding="0" cellspacing="0" width="50%">
<thead>
<tr>
<th>Annual</th>
<th>Semi-Annual</th>
<th>Quarterly</th>
<th>Monthly</th>
</tr>
</thead>
<tbody>
<tr>
<td>#Model.PAN</td>
<td>#Model.PSA</td>
<td>#Model.PQT</td>
<td>#Model.PMO</td>
</tr>
</tbody>
</table>

Use dropdownlistfor with foreach in Asp.Net MVC View?

I have a View with a foreach loop for a list property of the model. Now, I want to be able to let the user set the value of each of the items in the list using a dropdownlist. But I'm not sure how to do that. I've used something like this when it is not in a foreach loop:
#Html.DropDownListFor(model => model.Level, new SelectList(new[] { 1, 2, 3, 4, 5 }, Model.Level))
But how do I do this when I need to reference item.Level in the loop instead? Here's my View code:
<div id="formDiv">
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Ny arbetserfarenhet</legend>
<table>
<tr>
#*<th></th>*#
<th>
Program
</th>
<th>
Nivå
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#item.Program.Name
</td>
<td>
#item.Level
</td>
</tr>
}
</table>
</fieldset>
}
</div>
I have a View with a foreach loop for a list property of the mode
I would recommend you to avoid writing loops in your views in favor of editor templates. So:
#model IEnumerable<AppName.Models.ModelName>
<div id="formDiv">
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Ny arbetserfarenhet</legend>
<table>
<tr>
<th>
Program
</th>
<th>
Nivå
</th>
</tr>
#Html.EditorForModel()
</table>
</fieldset>
}
</div>
and in the corresponding editor template (~/Views/Shared/EditorTemplate/ModelName.cshtml):
#model AppName.Models.ModelName
<tr>
<td>#Model.Program.Name</td>
<td>
#Html.DropDownListFor(
model => model.Level,
new SelectList(
Enumerable.Range(1, 5).Select(x => new { Value = x, Text = x }),
"Value",
"Text"
)
)
</td>
</tr>
So the editor template will be rendered for each element in your model (which is a collection of some type). The important part is that the editor template must be located in ~/Views/Shared/EditorTemplates and named XXX.cshtml where XXX is the type name used in your main view model collection.
Have you tried:
#Html.DropDownListFor(m => item.Level, new SelectList(new[] { 1, 2, 3, 4, 5 }, item.Level))
use this syntax:
#Html.DropDownListFor(model => model.Level, new SelectList(Model.level as System.Collections.IEnumerable, "VALUE_FIELD", "TEXT_FIELD", YOUR PROPERTY NAME)
MVC will create the loop. Just use an editor template, partial view in special folder, and the rest works like magic.
Editor Template
#model Models.AdditionalAccountingLine
#Html.HiddenFor(m => m.IsRequired)
#Html.DropDownListFor(m => m.FieldValue, new SelectList(#Model.FieldValueOptions, "Key", "Value"), "")
View
#Html.EditorFor(m => m.AdditionalAccountingLines);

ASP.NET MVC3 Deleting a record using a sub-form

I am trying to delete a record being displayed in a table on my ManageUser view using a sub-form, thus
<table cellpadding="2" cellspacing="0" border="1" summary="User Grid" style="text-align: left">
<tr style="background-color: #ABC3CB;">
<th align="center">User Name</th>
<th align="center">Approved</th>
<th align="center"> </th>
<th align="center"> </th>
</tr>
<% foreach(MembershipUser membershipUser in ViewData.Model) { %>
<tr>
<td><%: membershipUser.UserName %></td>
<td align="center"><%: Html.CheckBox(" ", true, membershipUser.IsApproved ) %></td>
<td align="center">
<% using (Html.BeginForm( "DeleteItem", "Admin", new { id = membershipUser.UserName } )) { %>
<input type="image" src="<%: Url.Content( "~/Content/Images/Delete.jpg" ) %>" />
<% } %>
</td>
</tr>
<% } %>
</table>
The ManageUser view is displayed by the following code in the AdminController, thus
public ViewResult ManageUser( string searchType, string searchInput )
{
List<SelectListItem> searchOptionList = new List<SelectListItem>()
{
new SelectListItem() {Value="UserName", Text = "UserName"},
new SelectListItem() {Value="Email", Text = "Email"},
};
ViewData["searchOptionList"] = new SelectList( searchOptionList, "Value", "Text", searchType ?? "UserName" );
ViewData["searchInput"] = searchInput ?? string.Empty;
ViewData["searchType"] = searchType;
MembershipUserCollection viewData;
if (String.IsNullOrEmpty( searchInput ))
viewData = Membership.GetAllUsers();
else if (searchType == "Email")
viewData = Membership.FindUsersByEmail( searchInput );
else
viewData = Membership.FindUsersByName( searchInput );
ViewData["PageTitle"] = "Account Management";
return View( viewData );
}
When I display the page, and select the Delete choice, I expect it to run Admin/DeleteItem in the AdminController, thus
public RedirectToRouteResult DeleteItem( string id )
{
Membership.DeleteUser( id );
return RedirectToAction( "ManageUser" );
}
but instead, it is returning directly to the Admin/ManagerUser view, thus displaying my original set of records again.
I have obviously missed something but I cannot see what. Anybody help?
HTML <form> elements cannot be nested. Nesting them results in unexpected behavior which could vary between different browsers. Quote from the specification:
Every form must be enclosed within a
FORM element. There can be several
forms in a single document, but the
FORM element can't be nested.
So you might need to remove the outer form or find another way of organizing your markup.

Resources