mvc-3 dropdown binding-razor - asp.net-mvc-3

I have a table in the database called Person and it has various fields like id(Guid), forename and lastname. I am pulling them from the database using the following code
There is a method called GetAll, Which returns the List items.
In controller:
ClassService p= new ClassService();
ViewData["Id"]= new SelectList(p.GetAll(),"id","Forename");
In View:
#Html.DropDownList("Id_0",((SelectList)ViewData["Id"]).Items,"none")
It complains that there is acompilation error.What is wrong in there? and if it compiles does it loads into the dropdown box?
Could anybody tell is this correct of doing it or am I missing anything.
Thanks

Html.DropDownList() takes the name you want the select to be called and then an IEnumerable of SelectListItem(). Remove the .Item second parameter and it should work. The third parameter is the value of the selected item. So I am not sure what passing "none" will do other than not select anything in the dropdown list.
Also I am not sure how you will be handling the binding to a model when you post the form. Dont forget to have a integer called Id_0 as a parameter to the [HttpPost] action menthod.

Related

How can i do a dynamic SelectOneRadio in ADF with CollectionModel binding?

im trying to do a SelectOneRadio that was linked with a binding in ADF.
Mi binding have this structure:
Parent named "Group" (ID, Group, Orden).
Child named "Action" (ID, Action, Desc).
I want one radio group for each "Group" with each "Action".
The web don't have error or i cant see it.
And if i can do this, can i get the value of each radio group?
Thanks for all.
I will first check if the value set on af:iterator is returning expected number of values/rows/items. Then I will check if each of those row item has children property, and see if that too is type of List (or related types). If you follow these two instructions, you will know why this isn't working.

creating a form field populated by a relationship in Laravel 4

I am trying to build a form for a Happening. The Happening references a Places table by place_id.
e.g. happening "OktoberFest" has a place_id 123 which corresponds in table Places to München
These are the relationships declared in the models:
For model Place:
public function happenings()
{
return $this->hasMany('Happening');
}
For model Happening:
public function place()
{
return $this->belongsTo('Place');
}
model Happening has a place_id field linking it to Place.
I am also using {{Form::model($happening, array('route' => array('happenings.update', $happening->id)...}} as form opening
Problem 1: how to create a {{Form::text('......')}} that will be properly prefilled with München when editing the happening Oktoberfest ?
Problem 2: I was trying to get that field to work as an ajax autosuggest (i.e. starting to pull suggestions from the Places table as soon as 3 characters have been entered). I have checked a few implementations but they don't seem to mix correctly with Problem 1
To try and solve Problem 1, I have tried the solution here
Laravel 4 Form builder Custom Fields Macro
but I was unable to make it work.
Long question, it's my very first on stack overflow, please be patient :)
If a Happening is linked to Place via the column 'place_id' you have to supply an id to save in your model/table.
There are a couple of ways that I can think of:
make a list of availble Places in a radio of select, the name will be 'place_id', the value the id of the Place en something like title for the value.
instead of displaying radio's or a select a textfield with autocomplete is a great solution if you got a lot of places. I won't go into detail how to implement it but the general idea is to autocomplete the typed in placename and on selection of that place to put the id of that place in a hidden field named 'placed_id'
After saving the form save your model with the posted place_id
(and check that id if it's valid and existing, never trust user input )

How to prevent user from modifying some fields on the form?

I am using MVC3 and EF4 to write a web application. I am using an action header like below to capture the form values submitted by the user.
<HttpPost()>
Public Function Edit(ByVal prod as Product) As ActionResult
I use the below code for updating the record.
db.Attach(prod)
db.ObjectStateManager.ChangeObjectState(prod, EntityState.Modified)
db.SaveChanges()
I get the submitted values in prod object which I update in the database. The problem is that there are some users who are not allowed to modify certain fields in a Product, say ProductCost. I have disabled the textboxes for such fields in the HTML. But since it is clientside, the user can easily enable it using some tool like Firebug and modify the value.
The only solution I could come up was to retrieve the existing record from the database and copy its ProductCost value into prod.ProductCost. But I don't like firing a query for achieving this. Is there a better way to achieve this?
Edit: I found the below link to update particular fields. How to update only one field using Entity Framework?
You can use the below code to modify a particular field.
context.ObjectStateManager.GetObjectStateEntry(user).SetModifiedProperty("FieldName");
Now the question is do I have to write the above statement for every field the user is able to modify? If yes, suppose the Product model has 10 fields (1 primary key) and the user is allowed to modify all of them except the primary key, I need to write 9 statements?? Is there a method where you can specify multiple properties at once. Or even better something where you specify the properties which are not modified. (Note: I know I can run a loop over an array of field names to avoid writing 9 statements. I am asking for an alternative method and not refactoring the above)
Never trust client data. Always have your server code to validate the input and do appropriate actions.
I would create separate overloads of my Respiratory method update the product in different ways and then check what is the current user's access type, If he is admin, i will call the overload which updates everything, if he is a manager, i will call the method which updates name,imageUrl and price and if he is an employee, i will call the method which updates only name and ImageURL
[HttpPost]
public ActionResult Edit(Product prod)
{
if(ModelState.IsValid)
{
string userType=GetCurrentUserTypeFromSomeWhere();
if(userType=="admin")
{
repo.UpdateProduct(prod);
}
else if(userType=="manager")
{
repo.UpdateProduct(prod.ID, prod.Name, prod.ImageUrl, prod.Price);
}
else if(userType=="employee")
{
repo.UpdateProduct(prod.ID, prod.Name, prod.ImageUrl);
}
return RedirectToAction("Updated",new {id=prod.ID});
}
}

Retrieve Selected Item from Dropdownlist In MVC 3 Razor

I have a list in the controller and my code looks like this.
ViewBag.Organizations = _frontendUserService.GetOrganizationByClientId(Constants.ClientId);
And I'm setting this list in my View Page with a Dropdownlist.
#Html.DropDownListFor(
model => model.Organization.OrganizationId,
new SelectList(
ViewBag.Organizations as System.Collections.IEnumerable,
"OrganizationId",
"OrganizationName"),
"-- Select Organization --")
Here I get the OrganizationId as the selected item. Instead I want to retrieve the selected item as an "Organization" object in the POST request to my action method.
Actually why I wanted to get the entire object here is, because when I'm querying the database by OrganizationId I'm getting following error.
Error: sequence contains more than one matching element
In my application I'm using repository pattern.
It could be done, but I don't see the point in it. It's most likely a lot more efficient to fetch it from the database again instead of trying to do what you are asking.
I was trying to do something similar, but struggled - ended up using some of the code of this site and the generator tool, works quite well: http://www.mvc3razor.com/sample-code/

problem with 'datatable' jquery plugin and two table (ajax related)

i have two tabs that their content loads by ajax. both have a table in their content. i want to apply 'datatable' jquery plugin to both table. tables have the same id because they are create by a function.but their rows are different.
datatable plugin is applied to first tab table well but on the second one give this error:
"DataTables warning (table id = 'dttable'): Cannot reinitialise DataTable.
To retrieve the DataTables object for this table, please pass either no arguments to the dataTable() function, or set bRetrieve to true. Alternatively, to destory the old table and create a new one, set bDestroy to true (note that a lot of changes to the configuration can be made through the API which is usually much faster)."
i use "bDestroy":true in datatable plugin define.but in this way the plugin doesn't show in second table.
would you help me?
Your problem is that both tables have the same ID, which is invalid HTML. When you try to initialize the second Databable, your selector only finds the first table and tries to initialize Datatables on the first table again, which results in the error that you are getting.
You need to change your function to create each table with a unique ID and initialize each table by its respective ID.
Why not set the Datatables by a className rather than ID then it can apply to both of them?
When retrieving the data you can use something like $('.dataTableStyle').eq(1) to get information from the relevant one.
I'm using mvc3 and my problem was with initializing a dataTable in a view, then rendering a partial view with another dataTable. The issue was not in the id's of the 2 tables, but in the way the partial views get rendered in the framework. In my case, I had to move the script, or reference to the script, into the view that hosts the partial view. I had an issue similar to this using the Google Maps api.
try this code
$(document).ready(function() {
oTable = $('#DataTables_Table_0').dataTable({ //DataTables_Table_0 <-------table id
iVote: -1, //your field name
"bRetrieve":true
});
oTable.fnSort( [ [1,'desc'] ] );
});
use this in function event when you would change your table data
$('#tbl_resultates').dataTable().fnDestroy();
and add
"bRetrieve": true,
in
$('#tbl_resultates').dataTable({

Resources