Hi,
I have a form for create/edit articles. Every article is associated with an user.
After article is publshed the link to each article is composed from user name and article title (and {userName}/{articleTitle} should be unique combination):
/articles/{userName}/{articleTitle}
Article class:
public class Article
{
public int ArticleId { get; set; }
[Required(ErrorMessage = "Please enter title")]
public string Title { get; set; }
[Required(ErrorMessage = "Please select a user")]
public int UserId { get; set; }
}
View model:
public class ArticleFormViewModel
{
public Article Article { get; set; }
public SelectList Users { get; set; }
public ArticleFormViewModel(Article article, Dictionary<int, string> allUsers)
{
Article = article;
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem() { Value = "", Text = "Please select a user" });
foreach (var user in allUsers)
{
list.Add(new SelectListItem() { Value = user.Key.ToString(), Text = user.Value });
}
Users = new SelectList(list, "Value", "Text", Article.UserId);
}
}
View:
<div id="validationSummary">
<%= Html.ValidationSummary("Please correct the errors and try again.") %>
</div>
<% using (Html.BeginForm()) {%>
<%= Html.Hidden("ArticleId", Model.Article.ArticleId) %>
<fieldset>
<legend>Article</legend>
<ul>
<li>
<label for="UserId">User: <%= Html.ValidationMessage("UserId", "*")%></label>
<%= Html.DropDownList("UserId", Model.Users) %>
</li>
<li>
<label for="Title">Title: <%= Html.ValidationMessage("Title", "*") %></label>
<%= Html.TextBox("Title", Model.Article.Title) %>
</li>
</ul>
<input type="submit" value="Save" />
</fieldset>
<% } %>
<%= Html.ClientSideValidation(typeof(Article))
.AddRule("Title", new RemoteRule(Url.Action("ValidateTitle")))
.UseValidationSummary("validationSummary", "Please correct the errors and try again.")%>
I'm using xVal for validation.
ValidateTitle - is a controller action which validates that {userName}/{articleTitle} is unique. It works using Ajax.
Everything works fine when I'm editing title, but I have problems when I change the user in select list. If title was invalid for user1, and I choose user2, previous error message remains and I can't check that title for user2 is valid.
I can validate user name the same way I do it with title, but there will be cases when 2 errors saying that user name and title combination is invalid will be shown.
Title errors and user errors should be synchronized, but how?
Or maybe there is another way I should work with title and users list?