Retrieving values from multiple tables and displaying in a strongly typed View using List data class - asp.net-mvc-2

I have a table named Courses,CoursePreRequisites and a third tale named PreRequisiteTracking.One particular Course can contain multiple PreRequisites and so I couldn't pass a foreign key in the Courses tables and instead created the PreRequisiteTracking table.
Eg:A Course,say, Introduction to Java.This may have the following prerequsites:OOPS,Basic Programming Knowledge.
These prerequisites are given in checkboxes while creating a new course.
Now my problem is how do I join all these tables and list them in a View.
I joined all theses tables but since only Ids are being passed I am not able to retrieve the PreRequisites to show in the View.
Kindly help me,Thanks in advance

I got the answer to my post.
What I did was in my Class I declared a property as :
enter code here
`public class CourseModel{`
`public string coursename{set;get;}`
`public string coursecode{set;get;}`
`public string Benefits{set;get;}`
`public IEnumerable<CoursePreRequisites> display{set;get;}`
}
Here CoursePreRequisites is of table whose value i wish to display in the view.
Then in my controller in the Details action I gave:
enter code here:var query=(from cours in db.courses
join level in db.courselevels on cours.levelid equals level.levelid
where cours.courseid==id
select new CourseModel
{
coursename=cours.CourseName,
coursecode=cours.CourseCode,
Benefits=cours.Benefits,
display=(from courss in db.course
join track in db.prerequisitetrack on courss.CourseId equals track.CourseId
join prerequistes in db.courseprerequisite on prerequistes.prerequsiteId equals track.prerequsiteId
where track.courseid==id select prerequsite).AsEnumerable()
}).First() as Models.CourseModel;
Then create a strongly-typed view of Class type and give :
enter code here:<%foreach(var item in Model.display) {%>
<%:item.PreRequisites %>
Hope this will be useful to others.I tried and it worked for me.

Related

web2py: customizing form.vars to pass inputs id

I'm building a web app using web2py for attending employees.
this is the db in the model
db.define_table(
'employee',
Field('name'),
format = '%(name)s'
)
db.define_table(
'attendance',
Field('employee_id',db.employee),
Field('attend','boolean'),
Field('comments','text')
)
This is the controller:
employeeIDS=db(db.employee).select(db.employee.ALL)
table=[]
for eid in employeeIDS:
table.append([eid.name,INPUT(_type="checkbox",_name=eid.id,_id=eid.id),INPUT(_type="text",_name="comments",_id=eid.id)])
form=FORM( TABLE(TR("employee name","attended?","comments"),*[TR(*rows) for rows in table]),INPUT(_type="submit",_value="SUBMIT"))
if form.accepts(request,session):
response.flash="form accepted"
print(request.vars)
elif form.errors:
response.flash="form is invalid"
else:
response.flash="please fill the form"
return dict(form=form,vars=form.vars)
My question is this:
How can I access the id of the attend and comments fields in each row to associate these fields with the related employee. So, when I insert the form.vars to the attendance table, I guarantee that each employee recorded as attendance or absence and the related comments will inserted too.
Thanx
Instead of giving each comments input the same name, make the names unique, including the record ID as part of the name:
INPUT(_type="text", _name="comments_%s" % eid.id)
Then you will have form.vars.comments_1, form.vars.comments_2, etc.
As an aside, note that HTML id attributes should be unique, but you are using the value eid.id as the id attribute of both the checkbox input and the comments input.
I think a better choice is to use SQLFROM instead of FORM.
There you can customize the resulting form in the view right the layout you want to, even with HTML helper for tables, you have already used.
Please have a look at the signature of the SQLFORM - it offers a lot options as labels or showid (following the link just scroll down a little).
To exclude a field of being changed or even displayed in the SQLFORM use:
db.my_table.a_field.writable = False
db.my_table.a_field.readable = False
as described here - it's the same for SQLFORMS.

How can I pull data in a controller and form for one model that is in a different model with out a foreign key relationship?

I am new to rails and haven't really done to much with data outside of the model.
I have a form that references a table controller for files. I want to add an dropdown that will display a list of projects from a project table for the user to assign a the file to a project if they want too. Assigning a project is not a requirement. The file can be unassigned to a project. I do have a project_id column in the file table for those projects assigned but it is allowed to be null and I did not build a relationship because I need to have cases where there are none.
Can someone please tell me how to do this?
When they evaluate the file, the screen posts back with a save or update button depending if it has already been saved in the database.
At the same time as the save and update pop up on the right I want to display a list box of the projects with an assign project button. If new just a list, if update either just a list because not assigned or display the selected value in the list if already assigned, while allowing them to change it from the list if desired.
In the file controller method that posts back to the UI I have this code:
#file_alias_filedata = FileAliasFiledata.all
#projects = Project.all
for update
#projects = Project.find(params[:id])
In the form I have this code:
<p> <label> Select Project to Assign:</label> <br />
<%= select_tag 'projects', (#projects.present? ? options_for_select(#projects, #selected_project) : []) %> </p>
The form runs but I get this in the dropdown box:
#<Project:0x))7ff531ab4518>
Can someone please help me figure out how to accomplish my task and why I see the strange box value?
What am I doing wrong?
Thank you for your help!
Assigning a project is not a requirement. The file can be unassigned
to a project. I do have a project_id column in the file table for
those projects assigned but it is allowed to be null
From the docs:
belongs_to(name, scope = nil, options = {}) public
Specifies a
one-to-one association with another class. This method should only be
used if this class contains the foreign key. If the other class
contains the foreign key, then you should use has_one instead. See
also ActiveRecord::Associations::ClassMethods’s overview on when to
use has_one and when to use belongs_to.
Methods will be added for retrieval and query for a single associated
object, for which this object holds an id:
association(force_reload = false)
Returns the associated object. nil is returned if none is found.
Likewise,
has_many(name, scope = nil, options = {}, &extension) public
Specifies
a one-to-many association. The following methods for retrieval and
query of collections of associated objects will be added:
collection(force_reload = false) Returns an array of all the
associated objects. An empty array is returned if none are found.
But belongs_to() and has_many() are supposed to make things more convenient for you. You certainly do not have to use them.
Next,
and why I see the strange box value? What am I doing wrong?
You see the strange value for the same reason the following two loops display different things:
class Dog
attr_reader :name
def initialize(name)
#name = name
end
end
#dogs = [
Dog.new("Sam"),
Dog.new("Betty"),
Dog.new("Pete"),
]
#dogs.each {|dog| puts dog}
#dog_names = #dogs.map {|dog| dog.name }
#dog_names.each {|dog_name| puts dog_name}
--output:--
#<Dog:0x0000010099a308>
#<Dog:0x0000010099a2b8>
#<Dog:0x0000010099a268>
Sam
Betty
Pete
You will see the same result if you do something like the following in a view:
<div>
<%= select_tag "dog", options_for_select(#dogs) %>
</div>
<div>
<%= select_tag "dog_name", options_for_select(#dog_names) %>
</div>
If you read the docs here:
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_for_select
...you will see several examples, which should make it clear that options_for_select() takes an argument that is:
An array of Strings.
A Hash where both the keys and values are Strings.
An enumerable that iterates over some Strings.
etc.
Do you see a pattern? It's Strings! options_for_select() needs an argument that consists of Strings. If the argument is not a collection of Strings, e.g. an array of project objects, then options_for_select() tries to convert the objects to strings by calling to_s() on the objects. And the default to_s() method is Object#to_s() which is inherited by all objects and produces a string containing the class name and the object_id.
I am also new to rails, but I think you can try using the options_from_collection_for_select method.
<%= select_tag :search_state, options_from_collection_for_select(State.find(:all, :select => :name), :name, :name) %>
Hope this help. Cause it certainly helped me.

Get value from Entity Framework for Dropdown List and Return selected value in MVC

Assuming i got a table called Countries and using Entity Framework, i want to know how could i populate the available countries (listed in the table countries) to view as drop down list and return the value to HTTPPost Controller
i got
public ActionResult SignUp()
i think the populate code should be here but i not sure
how to retrieve from entity framework and populate into view
and
[httpPost]
public ActionResult SignUp()
i want to read the user selected value and i think is
int value = form["DropDownListName"].SelectedIndex + 1;
can anyone please guide me on this with some hint or example , please ? Thx a lot =D
To be honest, you're not really working in an MVC pattern here. Don't put UI construction logic in your constructor.
Rather, expose the ID that you want to bind to the list via a model that you pass to a View() method in your constructor.
In your view, use the name of that property as the Name of a Drop-down and create a helper class to generate the list of values.
I'd give you a more specific example, but I'm in the cinema with my iPad, so a bit stuck for access to Visual Studio at the moment!

cakePHP: automagic form elements, populating selection list

I have two tables, users{name,id,age_range_id} and age_ranges{id,range_name}.
There are also two models, controllers and the proper view files.
In the views I have the adduser.ctp file, which hold the proper form.
What I want is to have an input (select) that will hold the options from age_ranges.name field.
So, in the users model I've added var $hasMany = 'age_ranges';
What's next?
I know that I can use the $this->set to store the options as an array in the controller and then use it in the view.
but I assume(wrongly?) that by relating the models there is an 'automatic' way to do it.
Which lead me to the question: how?
I won't repeat what Thorpe and dogmatic have already written. They are both correct.
However, although it's difficult to be sure without seeing your model files, commonsense tells me that in the User model the relationship should be User:hasOne:AgeRange and in the AgeRange model it is AgeRange:hasMany:User, not the other way round as you have written.
Also, you do not specify the table name ('age_ranges') in the relationship, but the Model name ('AgeRange').
See these pages in the manual:
http://book.cakephp.org/view/1001/Understanding-Models & http://book.cakephp.org/view/1039/Associations-Linking-Models-Together
add $this->set('ageRanges', $this->User->AgeRange->find('list')); to the controller action
then add $this->Form->input('age_range_id') to the form
You can do this:
$this->User->AgeRange->find('list') and pass that to the view for a select statement

ValidationMessageFor returns no information when calling modelState.AddModelStateError

I created a class that implements the IModelBinder interface. Within a method of that class I basically retrieve some values and try to validate them. If the validation fails, I add update the model state with necessary information like below:
DateTime mydate;
if (!DateTime.TryParse(convValue,out mydate))
{
bindingContext.ModelState.AddModelError("Date", "Date was crap");
}
The problem is that Html.ValidationMessageFor(m => m.Model) returns no value. I looked at the MVC source code and found out that a proper key with id "Date" can't be found in the ModelState dictionary.
Why is that ? The controller that returns the view have access to the model state and can enumerate over ModelState.Errors
Thanks,
Thomas
Is "Date" the name of the property you are validating?
The first parameter of ModelState.AddModelError should either be the name of the property you want the validation message to display for, or left as string.Empty if you only want the error to display in in the validation summary.
If you want to display an error message that isn't tied to a specific property of your viewmodel, you could call <%: Html.ValidationMessage("Date") %> in your view to display that particular message if it has been set.
Edit: just realised how old this question is. Ah well, might come in handy anyway...