Use DataAnnotations to force a DropDownList populated from my model - entity-framework

Is there a way use DataAnnotations to tell Razor to render a DropDownList and populate the choices from a specific field in a specific entity?
Specifically I am capturing a "Calendar Year" property in my View and would like it to be a DropDownList. I am doing this currently by passing the years into my view via the ViewBag and then calling "DropDownListFor". I was hoping for a way to define it in my ViewModel and them simply call "EditorFor".
Thanks!

I can't find a way to do it with a DataAnnotation, but you don't need to use the ViewBag, you could pass the values in, like this:
#Html.ListBoxFor(m => m.SelectedFoos, Model.AllFoos.Select(f => new SelectListItem { Text = f.Name, Value = f.ID }))
(Note: This uses ListBox, taken from an answer here, but should be similar for DropDownList).

Related

Apps script: use a form as a template for other forms creation

I have a form with a set of questions, and I want to use it for other forms creation. In other words, I want to iterate through this template form items, choose those that I need and append them to another, newly created form.
I had no problem with getting the items and choosing those that I need; however, I can't find the way to append these items to another form - all of the Form.addSomethingItem() methods don't take arguments (docs for example). Is it really impossible, or do I miss something foolishly simple?
There are two ways to achieve this:
Make a copy of the form using DriveApp and remove/modify items in-place on the new form copy.
Iterate over existing items, check it's type and add them to the new form. For example, The following gets Item1's enum and converts it to a camelCase string and executes add{Type}Item method, where Type is MultipleChoice in case of MULTIPLE_CHOICE Enum Item type.
const newForm2Item0 = Form2[
`add${String(Form1.getItems()[0].getType())
.toLowerCase()
.replace(/(^|_)[A-Z]/gi, match =>
match.toUpperCase().replace('_', '')
)}Item`
]();//equivalent to Form2.addMultipleChoiceItem()
You would then add choices and other configurations as needed in a similar manner.
Form methods like addTextItem() don't take arguments, rather they return Items classes (e.g. TextItem). Those Item classes have their own methods for assigning properties to a question on a form.
Examples
here's an example of adding a text item with a specific title
form.addTextItem().setTitle('I am a text question title');
here's an example of adding a multiple choice item to a form with some choices
var item = form.addMultipleChoiceItem();
var choices = ['choice 1', 'choice 2', 'choice 3'];
choices.forEach(function(choice) {
item.createChoice(choice);
})

MVC4 edit method changes values to null if correspndong fields don't exist in the form

My table has two columns CreatedBy and CreateTime. In my view form, I don't have these fields. Now when I update a record using ASP.NET MVC4 Edit (post) method, these columns are set to null. But I want to retain the values. I know in my Edit (post) method, I can retrieve the record from the database and set these manually. But I am wondering whether I can ask Entity Framework not to change the values of these fields.
No you can't, if you want to keep the old values then you have to get the record first and then manually assign the values that you want to update. The only other way is to go through your entity property by property and tag which ones you want to modify, like so:
db.MyEntity.Attach(myEntity);
db.Entry(myEntity).Property(e => e.MyProperty).IsModified = true;
db.SaveChanges();
either way you end up having to do the manual work yourself.
You have to choices here:
1) As #KennyZ mentioned, add to #Html.HiddenFor() somewhere in your view, into your form:
#Html.HiddenFor(m => m.CreatedBy)
#Html.HiddenFor(m => m.createTime)
2) You can manually update that entity and leave those two properties alone:
var ent = dbctx.Entities.Find(model.ID);
ent.Prop1 = model.Prop1;
// ... also for other properties except those two property
dbctx.SaveChanges();
Sure you can. I assume they are already in your model, just add them to the form with Html.HiddenFor(m => m.createdBy). Now they are in the form but not displayed, and still have values on Post methods.

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!

ASP.NET MVC - Display Model Fields without Updating Value

I am currently working on a strongly-typed update view in ASP.NET MVC2. In addition to properties the user can update, there are also some properties that the user should not be able to update, but I would like to display on the page anyway (for example, a created on date).
Here is an example of how I am displaying these non-editable fields:
<td>Created on:</td>
<td><%= Html.DisplayTextFor(model => model.CreatedOn) %></td>
However, when I submit the form and then use a breakpoint on the controller method to see the model object that is being passed to the method via a POST request, the non-editable fields are set to a null or empty value (for example, the CreatedOn date is set to 1/1/0001). The editable fields are being passed back with the correct values. How can I display these non-editable fields while retaining the original value when I post the form back to the controller?
You don't need the original value. If you use UpdateModel (or TryUpdateModel) you can set which properties should be updated. This solution is also a lot safer because you explicitly tell MVC which properties should be updated.
You would need to use a hidden field like so:
<%= Html.HiddenFor(model => model.CreatedOn) %>
This would be in addition to your display field.

JQuery validation based on class?

I have a form that will have dynamically created elements, one of those will be of date type. There can also be many fields of this type on my form, all which must be validated.
I am using a strongly typed view in Asp MVC, so the name will change based on various factors. What I would like to do is validate based on a class name instead, since that will be constant for that type of field.
Ie:
<%= Html.TextBox("questionAnswers[" + index + "].AnswerValue", qa.AnswerValue, new { #class = "DateTypeClass" })%>
So then I would need JQuery validation based on the classname DateTypeClass versus the Name.
Any ideas?
In your validation function you could check the value like so:
var dateFieldValue = $(".DateTypeClass").val();
//validate dateFieldValue here
Also you don't have to resort to selecting by class if you don't want to. If no other fields share this validation then you could select by partial id in jquery. That would look like this:
var dateFieldValue = $("[id^=someId]").val();
//validate dateFieldValue here
So you would if set someId on the field and ASP.Net adds some additional stuff to the id it will still select it properly. I don't use ASP.Net MVC so not sure where you are setting the ID (if at all)
Also if you want inline validation you can wireup the onBlur event like so:
$(".DateTypeClass").blur(function(){
//Call field validation function here
});