I really have no idea.
I am trying to return a view with results from a Joined Table.
I keep receiving this error:
"The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery`1[System.String[]]', but this dictionary requires a model item of type 'tacticMVC.crypto'. "
my controller code is as follows
Function Details(Optional ByVal id As Integer = Nothing) As ActionResult
If Request.IsAuthenticated = True Then
'Dim cryptoes = db.cryptoes.Where(Function(c) c.key_email = HttpContext.User.Identity.Name()).ToList()
'Dim crypto As crypto = db.cryptoes.Find(cryptoes(0).id_cypto)
Dim crypto = (From c In db.cryptoes
Join con In db.consumers On c.id_consumer Equals con.id_consumer
Where c.id_consumer = 3
Select {c.key_email})
Return View(crypto)
Else
Return HttpNotFound()
End If
End Function
If I use just the 2 commented lines in the function the view returns fine but of course I can only get the data from one table. I need to join the tables and then return the data.
I've tried adding .toList(), .singleordefault() etc - does not solve anything
the vbhtml file:
#ModelType tacticMVC.crypto
<h2>Details</h2>
#Using Html.BeginForm("Action", "Controller", FormMethod.Post)
#<fieldset>
<div class="display-label">
#Html.DisplayNameFor(Function(model) model.key_email)
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.key_email)
something
</div>
</fieldset>
#<p>
#Html.ActionLink("Edit", "Edit", New With {.id = Model.id_cypto}) |
#Html.ActionLink("Back to List", "Index")
</p>
End Using
You're returning a database query object directly, but your page's cshtml says it expects a typed ViewModel.
Where is tacticMVC.crypto defined and what does it look like?
Dim crypto does not mean "an object of type crypto", it means "A late-bound object named crypto".
Great! - Just like a lot of other experiences after spending hours on it I have worked it out immediately after I posted my question.
Answer:
Controller
Function Details(Optional ByVal id As Integer = Nothing) As ActionResult
If Request.IsAuthenticated = True Then
Dim cryptoes = db.cryptoes.Where(Function(c) c.key_email = HttpContext.User.Identity.Name()).ToList()
Dim crypto As crypto = db.cryptoes.Find(cryptoes(0).id_cypto)
Return View(crypto)
Else
Return HttpNotFound()
End If
End Function
vbhtml
<div class="display-field">
#Html.DisplayFor(Function(model) model.consumer.name_consumer)
</div>
I am open to a better solution
Thanks
Related
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".
Hi i want to dynamicly build a div layout depending on the data i send to view, i want make 2 rows of divs and when there is odd number of models sent to view i want the layout to close as you can see in the code every 2nd model or on last model and start div every odd model .... but when i uncomment the commented code there are errors ....
(if i am not mistaken something similar worked in with C# so i hope it's only synax error)
#For Each procesData In Model
curElement = curElement + 1
elemNumb = elemNumb + 1
If (curElement = 1) Then
'#<div id="row"> !Comented
End If
#<h3>Element number #elemNumb</h3>
#<h3>#procesData.Name</h3>
#<h3>#procesData.Status.ToString</h3>
#<br />
If (curElement = Model.Count) Then
If (elemNumb = 1) Then
'#</div> !comented
End If
End If
If (curElement = 2) Then
'#</div> !comented
elemNumb = 0
End If
Next
I tweaked .css file and i managed to 'avoid' my problem but if anyone knows how to solve this without bypassing the original problem i would be greatfull for answer :)
<div id="toggle">
#For Each procesData In Model
curElement = curElement + 1
elemNumb = elemNumb + 1
Dim idName As String = "element" + elemNumb.ToString
#<div id=#idName>
<div class="heading">
#procesData.Name ::::::: Status <img class="statusIMG" id=#procesData.Status.ToString align="right" src="/" />
</div>
<div class="content">
<p>
Dokladniejsze informacje o wskazniku (potrzebne bedzie id zeby wygenerowac partial view! zapamietac)
<br />
np.Html.ActionLink("Edit Me", "Edit", new { id=item.ID })
</p>
</div>
</div>
If (curElement = 2) Then
elemNumb = 0
End If
Next
</div>
I don't really know how to deal with the next issue :
So, I've a webbased application developped with ASP.NET MVC3, which is used to remember when an event is relayed to some people.
I've 3 tables
Contact
id_contact
name
firstname
...
event
id_event
...
transmission
FK_id_event
FK_id_firstname
mailed (boolean)
phoned (boolean)
For each event, I need to list all the contacts that are related to this event. And for each contact, I need to display 2 checkboxes that have to be checked if the contact has been called or mailed.
'
' GET: /Event/Details/5
Function Details(id As Integer) As ViewResult
Dim event As event = db.event.Single(Function(o) o.idOpportunite = id)
Dim contacts = (From a In db.contact, b In db.transmission
Where a.id_Contact = b.FK_id_contact And b.FK_id_event = id
Select a)
Dim transmission = (From a In contacts, b In db.transmission
Where a.id_Contact = b.FK_trans_cont
Select b)
Dim model = New EventDetails With {
.event= event,
.Contacts = contacts,
.TransOpp = transopp
}
Return View(model)
End Function
I don't know if the "transmission" part of the code is good or not.
Here in the view, this is were I display the contacts
#For Each contact In Model.contacts
#<tr>
<td>
#Html.ActionLink(contact.name + " " + contact.firstname , "Details", New With {.id = contact.idContact})
</td>
<td>
#Html.Raw(contact.phone)
</td>
<td>
#*Html.DisplayFor(Function(modelItem) currentItem.mail)*#
<a href=mailto:#contact.mail>#Html.Raw(contact.mail)</a>
</td>
<td>
***My checkboxes should be here***
</td>
</tr>
Next
So, my question is, what should I do to display those checkboxes?
(sorry if I'm not understandable, I'm not a native english speaker. Don't hesitate to edit my english mistakes (or the title which is not a great one)).
With the help of Yasser, I've done this :
#code
Dim mail As Boolean = (From a In Model.Event
Where a.FK_id_contact = contact.idContact And a.FK_id_event = Model.Opportunite.idOpportunite
Select a.mailed)
End Code
However, I get an error :
Value of type 'System.Collections.Generic.IEnumerable(Of Boolean)' cannot be converted to 'Boolean'.
Here is something that should help
#{
bool isMailed = // set values;
bool isPhoned = // set values
}
#Html.CheckBox("mailed ", isMailed );
#Html.CheckBox("phoned", isPhoned );
In your ContactViewModel you can have two properties
bool isMailed ;
bool isPhoned ;
Then you can query the database from your controller before you bind the viewmodel the view and set those parameters. For example if you are showing data for contact id = 1 and event id = 2, you can query the database table transmissions and find whether you have called or mailed before and update the variable in ContactViewModel.
then in your view you can bind the values to the checkbox as follows
#Html.CheckBox("mailed ", contact.isMailed );
#Html.CheckBox("phoned", contact.isPhoned );
if you want to update the mailed or phoned in the database you can do it using the above ViewModel by submitting data to the controller. from controller you can find what is the Event_Id, Contact_Id and mailed or phoned , then you can update the database accordingly
Good Morning everybody.
I'm a beginner in .Net languages and need an example to be able to go further.
So, my objective is to display dates and comments from a datatable, below general information about a client.
The view needs to become something like that :
name firstname :
adress :
phone number :
...
date1
comment1
date2
comment2
...
It was easy to automatically generate a strongly typed view with the general data. Now, I don't get how to display the comments below.
Here is what I've already done into the controller
' GET: /Contacts/Details/5
Function Details(id As Integer) As ActionResult
Dim contact As contact = db.contact.Single(Function(c) c.idContact = id)
Dim listMeet = New List(Of meeting)
listMeet = (From d In db.meeting
Where d.FK_meet_contact = id
Select d).ToList()
ViewBag.listeMeeting = listMeet
Return View(contact)
End Function
Into the view, I dis plenty of wrong things... Let's show you the last one :
#ModelType MvcApplication4.contact
#Code
ViewData("Title") = "Details"
Dim list As List(Of Object) = ViewBag.listeMeeting
Dim ligne As ListItemCollection
End Code
[...]
<fieldset>
<legend><button onclick="togglefield('Meet')">Meetings</button></legend>
<div class="Meet">
#For Each ligne In ViewBag.listeMeeting
#Html.Raw(ViewBag.listeMeeting)
Next (ligne)
</div>
</fieldset>
What haven't I well understood?
ps : I'm not a native english speaker, so, sorry if my english sucks
You could use a view model instead of ViewBag:
Public Class MyViewModel
Public Property ContactDetails As Contact
Public Property Meetings As IEnumerable(Of Meeting)
End Class
and then populate this view model in your controller and pass to the view for displaying:
Function Details(id As Integer) As ActionResult
Dim contact As contact = db.contact.Single(Function(c) c.idContact = id)
Dim meetings =
(From d In db.meeting
Where d.FK_meet_contact = id
Select d).ToList()
Dim model = New MyViewModel With {
.ContactDetails = contact,
.Meetings = meetings
}
Return View(model)
End Function
and then have your view strongly typed to the view model:
#ModelType AppName.MyViewModel
<h2>#Model.ContactDetails.SomePropertyOfContact</h2>
<fieldset>
<legend>
<button onclick="togglefield('Meet')">Meetings</button>
</legend>
<div class="Meet">
#For Each meeting In Model.Meetings
#meeting.SomePropertyOfMeeting
Next
</div>
</fieldset>
I'm developing a website for Tenants to find properties. When they sign up, they can choose the property types that they are interested, for example: Apartment or House.
When a Tenant logs into their account, they can then do a search for properties. The search form is prepopulated with the values that they originally entered on sign up, for example: City, Postcode and so on.
The form also needs to display some checkboxes with the relevant boxes ticked for the Property Types that they selected on sign up. I'm having some problems getting this to work and wondered if there is anyone who could correct the code for me?
I believe I need to use an 'IN' statement so that the relevant checkboxes would be ticked, if the IDs for those properties are found in the CustomerReqPropertyType column. The CustomerReqPropertyType column is varchar(50) and as an example, if a user has selected Apartment and House, it is store in the row as 2, 4 (as there is a separate table with the Property Types.
This is the code I have on the page;
<%
While (NOT rspropertytype.EOF)
%>
<li>
<input type="checkbox" name="txtPropertyType" id="txtPropertyType" value="<%=(rspropertytype.Fields.Item("PropertyTypeID").Value)%>"<% If Not rstenantrequirements.EOF Or Not rstenantrequirements.BOF Then %><%If (Not isNull((rstenantrequirements.Fields.Item("CustomerReqPropertyType").Value))) Then If (CStr(rspropertytype.Fields.Item("PropertyTypeID").Value) = CStr((rstenantrequirements.Fields.Item("CustomerReqPropertyType").Value))) Then Response.Write("")%><% End If ' end Not rstenantrequirements.EOF Or NOT rstenantrequirements.BOF %> />
<label for="txtPropertyType"><%=(rspropertytype.Fields.Item("PropertyTypeTitle").Value)%></label>
</li>
<%
rspropertytype.MoveNext()
Wend
If (rspropertytype.CursorType > 0) Then
rspropertytype.MoveFirst
Else
rspropertytype.Requery
End If
%>
I would be very grateful for any help.
In order for a checkbox to be checked the checked property must equal "checked".
e.g.
<input type="checkbox" name="something" value="somethingElse" checked="checked" />
I suspect that in your code the rspropertytype and rstenantrequirements recordsets could be consolidated into one recordset generated from one SQL statement.
e.g.
SELECT pt.*
, CASE
WHEN ISNULL(tr.CustomerReqPropertyType,0) = 0 THEN 0
ELSE 1 END AS [checked]
FROM propertytype AS [pt]
LEFT JOIN tenantrequirements AS [tr]
ON pt.PropertyTypeID = tr.CustomerReqPropertyType
WHERE ...
Then your ASP code could be simplified as well.
e.g.
<%
While (NOT rs.EOF)
Dim pID : pID = rs("PropertyTypeID")
Dim pTitle : pTitle = rs("PropertyTypeTitle")
Dim checked : checked = "" : If (rs("checked") = 1) Then checked = "checked"
%>
<li>
<input type="checkbox" name="txtPropertyType" id="txtPropertyType<%=pID%>" value="<%=pID%>" checked="<%=checked%>" />
<label for="txtPropertyType<%=pID%>"><%=pTitle%></label>
</li>
<%
rs.MoveNext()
Wend
%>
This is really hard to follow. First I'd break up that line to where your while is you can just set a variable and print that to page. I assume you're trying to set the checkbox checked. What I would do is make sure the value returned isn't null assuming this is a query that just returns the property type and you left joined it with the table that has the descriptions in it when they are set for the property in question. I don't see you ever print checked to the checkbox so it's never going to be checked anyway.