I get validation message always when I open this page (even first time), even if I choose value in one of dropdown lists, message doesn't go away. If I choose values in both I can submit form but messages still doesn't go away.
Snippet is Linq to sql class and LanguageID and SnippetTypeID are ints, I assume this happens because I pass empty model to View so LanguageID and SnippetTypeID are null and AFAIK Linq to Sql classes have required on non-nullable ints.
How can I fix this so validation messages doesn't appear before user tries to submit form, and if one of dropdown lists get selected to remove validation message.
View
#model Data.Snippet
#using (Html.BeginForm("Save", "Submit", FormMethod.Post))
{
<h1 class="subtitle">Submit new snippet</h1>
<h4>Title</h4>
#Html.TextBoxFor(snippet => snippet.Title, new { #class = "form-field" })
<h4>Language</h4>
#Html.DropDownListFor(snippet => snippet.LanguageID, new SelectList(#ViewBag.Input.Languages, "ID", "Name", #Model.LanguageID), "Choose Language", new { #class = "form-select" })
<p>#Html.ValidationMessageFor(snippet => snippet.LanguageID , "You must choose language", new { #class= "validation-message"})</p>
<h4>Snipet type</h4>
#Html.DropDownListFor(snippet => snippet.SnippetTypeID, new SelectList(#ViewBag.Input.SnippetTypes, "ID", "Name", #Model.SnippetType), "Choose snippet type", new { #class = "form-select" })
<p>#Html.ValidationMessageFor(snippet => snippet.SnippetTypeID,"You must choose snippet type", new { #class= "validation-message"})</p>
<h4>Text</h4>
#Html.TextAreaFor(snippet => snippet.Text, new { cols = "20", rows = "10", #class = "form-field" })
<input type="submit" value="Submit Snippet" />
}
Controller
//Controllers are not finished Save() should have
//code to actually insert to db after I fix validation
// GET: /Submit/
//
public ActionResult Index()
{
Snippet model = new Snippet();
SubmitModel input = new SubmitModel();
ViewBag.Input = input;
return View(model);
}
public ActionResult Save(Snippet snippet)
{
return View();
}
Model
Model is Linq to Sql class.
Snippet
ID (int, identifier)
Title (string)
SnippetType (int, FK on table SnippetTypes)
LanguageID (int, FK on table Languages)
Text (string)
Alright,
So I think the reason it is failing is because of the custom CSS that you are adding. ValidationMessageFor will put a hidden class when the validation is successful.
if you want to add custom colors or something like that with you CSS i would consider applying the style to the wrapping p tag or adding a wrapping div/span and adding it to that.
You could probably define your messages on the view using only #Html.ValidationMessageFor(snippet => snippet.SnippetTypeID, "ErrorMessage"); However a more proper way is to take your Model and create Data Annotations for it.
Take a look at this article http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-data-annotation-validators-cs for more information about how to do model validation with Data Annotations.
Also I would consider passing in custom classes instead of your linq to sql class so that you can do custom validation based on the view. These custom classes are often refereed to as ViewModels.
Related
I have this DropDownList in html where i can select the Texts.Text = Project, Value = ID
#Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, #class = "form-control" })
On click submit button in the controller I can see that the Value (ID) is passed on to be posted back to DB. I want the Text to be post into DB.
Controller side code line:
detailsConfig.Project = Convert.ToString(form["Project"]);
For example:
If the dropdownlist values are
Project ID
test 1
testagain 2
In controller I should get test, not 1. Please help
You use that drop-down change event and store that name in hidden filed and get that value to controller.
View:-
#Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, #class = "form-control",#id="ddlProject" })
<input type="hidden" id = "hdnProjectName" name="ProjectName" />
Jquery:-
$("#ddlProject").on("change", function () {
$("#hdnProjectName").val($(this).find("option:selected").text());
});
Controller:-
public ActionResult Save(FormCollection formcollection)
{
var projectName = formcollection["ProjectName"];
}
new SelectList(Model.dropConfig, "Project", "Project")
The above change solves my problem. Thanks #StephenMuecke :)
First, you should definitely strongly-type your dropdownlist to your model.
What I mean is this...
In the controller is where I would create the selectlist to be used in the view.
Controller
ViewBag.ProjectSelection = new SelectList(/* your data source */, "Project", "Project");
Disclaimer:
Submitting the Text value is not preferred because typically the Text value of the select element is not unique. Submitting the ID to the server is the best practice.. and then you can simply query the database based on the ID you submitted to get the values you want. This is the best way to get the most accurate and reliable data.
Then in your view, strongly-type your ProjectSelection selectlist to the Project property in your model.
View
#Html.DropDownListFor(model => model.Project, (IEnumerable<SelectListItem>)ViewBag.ProjectSelection, "-- Select LineID --", new { required = true, #class = "form-control" })
Why are you declaring required in the dropdownlist? That should be declared in your model.
Explanation
In MVC, when it comes to HTML elements where the user can select options to be submitted to the server (dropdownlist, listbox, etc).. only the Value will be submitted (which in your case was the ID). The Text portion of the element is just for the user to see to make their selection's easier.
Let me know if this helps!
I have a basic form allowing users to input details which then gets posted and saved to a database - this works as expected without any issues:
#model R32.Register.Models.RegisterCar
#{
ViewBag.Title = "Edit Your R32";
}
<h2>Edit R32</h2>
<div>
#using (Html.BeginForm("UpdateCar", "Garage", FormMethod.Post))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Enter details</legend>
<ol>
<li>
#Html.LabelFor(m => m.NumberPlate)
#Html.EditorFor(m => m.NumberPlate, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.NumberPlate)
</li>
<li>
#Html.LabelFor(m => m.Edition)
#Html.EnumDropDownListFor(m => m.Edition, "Select an edition:", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Edition)
</li>
<li>
#Html.LabelFor(m => m.Colour)
#Html.EnumDropDownListFor(m => m.Colour, "Select a colour:", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Colour)
</li>
</ol>
<input type="submit" value="Save Changes" />
</fieldset>
}
</div>
Model snippet:
[Required]
[Display(Name="Edition")]
public MkEnum? Edition { get; set; }
Enum:
public enum MkEnum
{
[Display(Name="Mk4")]
Mk4 = 1,
[Display(Name="Mk5")]
Mk5 = 2
}
The control renders as expected, with the Edition dropdownlist having three values: "Select an edition", "Mk4", and "Mk5".
The user is able to select an edition, control is validated, then posted to the controller.
The Post is successful, and all selected values are sent to the controller - the app then persists the data in a database, and so on, without any problems.
The issue is when I pass this model back into the same View to allow the user to edit the saved data, the saved values for the enums are NOT being set as the selected value in the dropdownlist.
I can confirm that any saved string values, such as NumberPlate in this example, are being passed back into the view and loaded into the UI.
Putting a breakpoint on the viewmodel as it renders I can confirm that my #model contains the saved values for enum properties - Edition for example - but the end result is that the "Select an edition:" dropdown list is rendered containing the expected dropdown values, but it's value is the default "Select an edition:" instead of the actual value passed in via. m.Edition.
I have been able to get this working using DropDownListFor - but am having difficulties in understanding why this is not working using EnumDropDownListFor, as this clearly seems like a more elegant solution.
Does anyone have any help/advice for this?
I just ran into this problem myself. This happens because fields of type enum are being passed back to the browser serialized as their enum names, but #Html.EnumDropDownListFor generates its option values as integers. The browser can't match up the two so the dropdown stays at its default selection.
There are 3 ways to get around this.
Get the view model's enum field to serialize properly as an int.
Write a dropdown generator that uses enum names as option values.
Use javascript to manually select the option (includes razor syntax here)
$("#YourDropdownID option").each(function () {
if ($(this).html() == '#(Html.DisplayFor(o => o.YourEnumFieldName))') {
$(this).attr("selected", "selected");
return;
}
});
Ok, so from what I could see the problem was caused by using an ActionLink to pass back the full model of an item being edited. Everything was being sent back in a Query string, so my Enum values were being passed to the controller in the following way: mkEnum=Mk4.
I was then loading the UpdateCar view as seen above in my example - but the query string values were being persisted in the call back to the View.
EnumDropDownListFor is unable to interpret/convert the text value of enums into their actual values - if I manually edited the Query string to mkEnum=1, then the correct value wasloaded into the ViewModel.
In addition to this problem, it was not a good solution passing the full model back to the controller.
I've modified the code to pass back a single Id of the item being edited - the controller then verifies the user has access to that Id, retrieves the Model from the Database then passes it back to the same View as in my above example.
With this change my dropdowns are now being updated with their values without any issues.
TLDR; If you experience this issue check to make sure you don't have model properties, specifically enum values represented by their string values, in a query string when loading your view and using EnumDropDownListFor.
I have a case where I have a page displaying an order and tabs that display the order details. The order details are quite complex and since they are the same layout, I want to use a partial view or editor template that will generate the form.
The problem is the result is multiple duplicate form input id's are generated (one for each order detail. For example, I have:
foreach (var orderDetail in Model.OrderDetils)
{
#Html.EditorFor(model => orderDetail, "WorkOrder", orderDetail)
}
I've read much about this and see solutions where it is recommended to use an editortemplate, but that solution only works when you have the same form to render, but passing it different model properties so the control id's prefixes will differ...ie. like this solution.
In my case, this won't work as the model property I am passing is always the same.
So how else can I create unique Id's in the partial or editor template that will also bind.
I know instead of:
#Html.EditorFor(model => model.WOHdr.Attribute1)
I could do:
#Html.TextBoxFor(model => model.WOHdr.Attribute1, new { id = Model.Id + "_Attribute1" })
But then it won't bind when it passes to the controller.
Thoughts?
Try this
#Html.TextBoxFor(model => model.WOHdr.Attribute1, new { #id = #Model.Id + "_Attribute1" })
Use "#"+dynamic value. Now You will get unique Id's
In EditorFor you can use like this
#Html.EditorFor(model => model.WOHdr.Attribute1, null, "id=" + #Model.Id + "" )
the id will generate like this
id="id_1", id="id_2" and so on..
<input id="Checkbox1_#(test.TestId)" type="checkbox" />
i hope upper code will help you
I have an MVC3 application with Razor and I created a View that inside renders a Partial View. This is how the main View looks like:
#{Html.RenderPartial("_SearchFilters", Model.SearchFilters);}
#* Other HTML elements *#
Inside the _SearchFilters Partial View I have the following DropDownLists inside a Form element:
Choose Year
#Html.DropDownListFor(m => m.Year, new SelectList(Model.YearsList, "Value", "Text"), DateTime.Now.Year)
Choose Month
#Html.DropDownListFor(m => m.Month, new SelectList(Model.MonthsList, "Value", "Text"), Model.Month.ToString(), new { #disabled = "disabled" })
<input type="submit" value="Display" />
I would like that upon Submit the two DropDownLists keep their status, namely the value selected by the user, when the View is reloaded with the filtered data.
Is there any way to do it without using AJAX?
UPDATE
The ViewModel is as follows:
public class TableSearchFiltersViewModel
{
public bool YTM { get; set; }
public int? Month { get; set; }
public int? Year { get; set; }
public IEnumerable<SelectListItem> YearsList
{
get
{
return Enumerable.Range(2011, (DateTime.Now.Year - 2011 + 4)).Select(m => new SelectListItem
{
Value = m.ToString(),
Text = m.ToString(),
}).OrderBy(m => m.Value);
}
}
public IEnumerable<SelectListItem> MonthsList
{
get
{
return Enumerable.Empty<SelectListItem>();
}
}
}
Thanks
Francesco
When you submit the form to the corresponding controller action, this action should take as input parameter some view model. This view model's properties will be bound from the input fields contained in the form including the selected value of the two dropdowns. Then the controller action could return the same view which will preserve the selected values of the dropdown boxes.
I would recommend you to use Editor Templates though instead of rendering partials as this will ensure proper naming of the dropdowns and eventually preserve selected values:
#Html.EditorFor(x => x.SearchFilters)
I don't have IDE at this time so couldn't test but this might work:
Choose Month
EDIT:
#Html.DropDownListFor(m => m.Month,
Model.MonthsList.Select(
t => new SelectListItem {
Text = t.Name,
Value = t.Value,
Selected = t.Value == Model.Month,
},
Model.Month.ToString(), new { #disabled = "disabled" })
Without ajax not, or you will have to repost the whole form. MVC is a web framework which is not dynamic like a winforms application. You will have to post the changes to your controller and reload the page with the necessary changes, or use ajax to reload these changes.
You could provide the default values for Year and Month properties (to be selected at the first request) and bind those instead of the hardcoded startup values you provided.
So instead of:
#Html.DropDownListFor(m => m.Year, new SelectList(Model.YearsList, "Value", "Text"), DateTime.Now.Year)
Which btw seems erroneous, as selected value (which I suppose DateTime.Now.Year is in your example) should be provided as SelectList's constructor (instead of DropDownListFor method's) argument. DropDownListFor method doesn't have a 'selected value' argument.
You could write:
#Html.DropDownListFor(m => m.Year, new SelectList(Model.YearsList, "Value", "Text", Model.Year))
and analogously in the second dropdown.
This will make dropdowns keeps the selected values when rendered using the posted model (as Model.Year and Model.Month would hold those). So you should make sure those values won't get overwritten with default ones after subsequent submits.
In MVC3, I've been able to rely on Html.DisplayForModel() to generate display's for my data. Using this method, and various templates, I have a single View for displaying several of my Models. What I'm wondering though, is there a way I can get this to work on Lists for my models?
For example, I have a model called Networks. My view to list out multiple networks looks like this:
#model PagedList<Network>
<div id="networkList">
#Html.Grid(Model).Columns(column => {
column.For(x => Html.ActionLink(x.Id.ToString(), "NetworkDetails", new { id = x.Id })).Named("Network ID");
column.For(x => x.Name);
column.For(x => x.Enabled);
}).Attributes(Style => "text-align: center")
#Html.AjaxPager(Model, new PagerOptions() { PageIndexParameterName="page", ShowDisabledPagerItems = false, AlwaysShowFirstLastPageNumber=true },
new AjaxOptions() { UpdateTargetId = "networkList" })
</div>
I'm wondering if it is possible to use a single template when generating lists for my models. I could rely on attributes to know which properties I would like to generate in my list, ie: [ListItem].
The head scratcher for me is, how can I pass a dynamic model to an extension method? If it's of any help, the Html.Grid extension is from MVCContrib. Has anyone else done something similar? It would be great to rely on a template as it would really chop down on the amount of code.
You can achieve it for EditorFor() using the following (it might be similar with your Grid extension method assuming it can take the template name parameter):
// in the main view
#Html.EditorFor(o => o.InvoiceId, "TemplateName", new { Property = "InvoiceId" })
#Html.EditorFor(o => o.Title, "TemplateName", new { Property = "Title" })
// in the template view
#model object
#{ var property = (string)this.ViewData["Property"]; }
Alternatively you can just pass in the name of the template and use this code in the template
var prefix = ViewData.TemplateInfo.HtmlFieldPrefix;
if (prefix.EndsWith("InvoiceId")) { ... }