ValidationMessageFor returns no information when calling modelState.AddModelStateError - asp.net-mvc-2

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...

Related

Lightswitch HTML Client, Set Default Value of List Picker

Lightswitch renders my navigation property as a list picker, but I can't figure out how to set a default value on it. There must be a simple way to do it. I've scoured the net, and all the suggestions look hopelessly kludgy. Is there a good comprehensive tutorial out there for Lightswitch? The most common tasks like setting the default value on a dropdown are ridiculously hard to figure out.
Here's how I did it.
myapp.Address.created = function (entity) {
myapp.activeDataWorkspace.MailListData.CountryRegion_LUs.filter("CountryRegionCode eq 'US'").execute().then(function (result) {
entity.CountryRegion_LU = result.results[0];
});
}
You want to write a handler for the created Javascript event for the parent entity. I'm binding CountryRegion_LUs, which are in the Address entity, so I am binding to the created event of the Address entity, not the CountryRegion_LUs entity. "MailListData" is the name of my database. I'm using an OData query to pull out the CountryRegion_LU that has a CountryRegionCode of "US." I could have simply used "load()" instead of .filter("CountryRegionCode eq 'US'").execute() to load all the records, and then picked the member of the result-set I wanted, say results.result[221], but then I'd be bringing all the data over and filtering client-side.
refer to this post of which I asked myself, there is a detailed answer on the problem you have above: it explains how to set your modal picker/details picker with a default value
Lightswitch HTML Client - set modal picker value when screen created
any questions feel free to ask

using Ajax , dropdownlist and page validation

using Ajax I filled Country, State and city dropdownlist. On land change state is filled and on state change city is filled properly.
Then when I try to save page I face this :Invalid postback or callback argument.
Searched and found out that this is due to change in ddl.selectedvalu change from initial value that is assigned by asp.net.
Now my question is that how can I let asp.net know that the new ddl value is valid?
Thank you.
In many pages it is recommended to use EnableEventValidation="false", but I prefer not to use it.
Some say that use Render and add value to notify .Net like this:
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
ClientScript.RegisterForEventValidation("ddlLanguages ", "English");
ClientScript.RegisterForEventValidation("ddlLanguages ", "Tamil");
ClientScript.RegisterForEventValidation("ddlLanguages ", "Hindi");
base.Render(writer);
}
but how to use it? where to put it?
for a better understanding I put here a sample code including Database script :
hesab20.com/DownLoad/Ajax.zip
in this sample Javascript is used to fill drop-down list . But when click button is executed and a post back occur, error happen.
Please help if you have experience with this.
Regards.
Please run the sample code and change the drop down lists , automatically the other is filled , meaning that list item text and value is completely changed. finally click button for a post back.
you must see that error happens:
Invalid postback or callback argument. Event validation ....
and note : EnableEventValidation="true"
Thanks

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.

MVC Html.textbox/dropdown/whatever won't refresh on postback

OK, let's start with the Html.Textbox. It is supposed to contain text read from a file. The file read is based on what the user picks from a dropdown list.
The first time it is fine. The user picks a value from the dropdown list. The controller uses that value to read some text from a file, and returns that text to the view via the view model. Everything is fine.
THen the user picks another value from the dropdown list. The controller reads a new value from a file and returns it via the view model. Debugging to the LINE BEFORE THE HTML.TEXTBOX is set in the view shows that the model contains the correct value. However, the textbox itself still shows the PREVIOUS value when the page displays!
If I switch from Html.Textbox to a plain input, type="text" html control, everything works fine. That's not so hard, but the same thing happens with my dropdown list -- I can't set the selected value in code. It always reverts to whatever was chosen last. Rendering a "select" tag with a dynamically-generated option list is a pain. I would love to be able to use Html.Dropdown.
What am I missing here?? This is such a simple thing in webforms!
When you post a form, the values that are posted are put into ModelState. When the HtmlHelper renders an html iunput element, e.g. Html.TextBoxFor(x => x.FirstName), it'll search various locations to get the value for the textbox... ModelState is before ViewData.Model in the list of locations. So there for, the previously posted value will appear in your textbox.
To fix this you could clear the ModelState value or update the ModelState value. BUT I would kinda view that as a hacky way of getting around the problem.
The real issue has more to do with the flow of the posts and requests. I would personally look into that and maybe implement the PRG (Post Redirect Get) pattern.
HTHs,
Charles
Following on from what Charles/Charlino said:
Model binding updates the ModelState object, which contains validation and model binding errors that are collected during model binding.
Inside an action method, model binding has occurred already to update the model, and generated the ModelState object. If you now update the value on the model inside the action, you must also manually update the model state (since the helpers use it to generate their HTML). Below is an example:
model.CaptchaIsValid = CaptchaService.ValidateAndExpireCaptcha(model.CaptchaAttempt);
if (!model.CaptchaIsValid)
{
ModelState.AddModelError("CaptchaAttempt", "Incorrect - please try again");
}
// I'll clear the value on each attempt, to force them to re-enter a CAPTCHA.
model.CaptchaAttempt = string.Empty;
// Since I updated the model, I must create a new ValueProvider result...
ValueProviderResult clearedValue = new ValueProviderResult(
model.CaptchaAttempt,
model.CaptchaAttempt,
CultureInfo.CurrentCulture);
// ... and update the ModelState's value.
ModelState.SetModelValue("CaptchaAttempt", clearedValue);
The biggest issue I see here is that you are trying to do a postback within MVC. That model is really not supported, and is actually way more trouble than it is worth (as it seems you are finding out). I would recommend using Ajax to update the contents of the dropdown dynamically.