(ModelState.IsValid) Property is not working properly in asp.net mvc4 with entity framework - asp.net-mvc-4

I have tried simple user log in using asp.net mvc4. I have used this condition (ModelState.IsValid), It was workiing before two days. Now i am trying to execute this program, But that property is terminating the condition. Please anyone help me to rectify this problem.
This is my controller code
{
[HttpPost]
[AllowAnonymous]
public ActionResult LogIn(Project.Models.Tbl_Users user)
{
int userid = user.UserID;
var sessionid = Session["userid"];
Session["RoleId"] = user.RoleId;
Session["Username"] = user.UserName;
var sessionval = Session["Username"].ToString();
if (!ModelState.IsValid)
{
if (Isvalid(user.UserName, user.UserPassword))
{
var db = new Project.Models.EntitiesContext();
var userroleid = db.Tbl_Users.FirstOrDefault(u => u.UserName == user.UserName);
Session["RoleId"] = userroleid.RoleId;
int sessionroleid = Convert.ToInt32(Session["RoleId"]);
FormsAuthentication.SetAuthCookie(user.UserName, false);
string sessionusername = Session["Username"].ToString();
if (sessionroleid == 1)
{
return RedirectToAction("adminpage", "LogIn");
}
else
if(sessionroleid==2)
{
return RedirectToAction("teammanager", "LogIn");
}
else
{
return RedirectToAction("userpage", "LogIn");
}
}
return View(sessionval);
}
return View();
}
private bool Isvalid(string username, string password)
{
bool Isvalid = false;
using(var db = new Project.Models.EntitiesContext())
{
var user = db.Tbl_Users.FirstOrDefault(u => u.UserName == username);
var pass = db.Tbl_Users.FirstOrDefault(u => u.UserPassword == password);
if (username != null)
{
try
{
if (user.UserName == username)
{
if (pass.UserPassword == password)
{
Isvalid = true;
//Session["RoleId"] = user.RoleId;
//int sessionid = Convert.ToInt32(Session["RoleId"]);
}
}
}
catch
{
//Response.Write("Login Failed For The User");
Isvalid = false;
}
}
}
}
This is my model
{
[Required(ErrorMessage = "User Name is Invalid")]
[StringLength(200)]
[Display(Name = "User Name")]
public string UserName { get; set; }
[Required(ErrorMessage = "Password Field is Invalid")]
[StringLength(50, MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string UserPassword { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
This is my view code
{
<form method="post" id="signin" action="#Url.Action("LogIn", "LogIn")">
<body style="background-color: Gray;">
<div>
<div>
</div>
#if (!Request.IsAuthenticated)
{
<strong>#Html.Encode(User.Identity.Name)</strong>
#Html.ActionLink("Log Out", "LogOut", "LogIn")
}
else
{
<fieldset>
<div>#Html.LabelFor(u => u.UserName)</div>
<div>#Html.TextBoxFor(u => u.UserName)
#if (Request.IsAuthenticated)
{
#Html.ValidationMessageFor(u => u.UserName)
#*#Html Session["Username"] = #Html.TextBoxFor(u => u.UserName);*#
}
</div>
<div>#Html.LabelFor(u => u.UserPassword)</div>
<div>#Html.PasswordFor(u => u.UserPassword)
#Html.ValidationMessageFor(u => u.UserPassword)
</div>
<div>#Html.CheckBoxFor(u => u.RememberMe)
#Html.LabelFor(u => u.RememberMe, new { #class = "checkbox" })
</div>
<div>
#Html.ValidationSummary(true, "Login Failed")
</div>
<input type="submit" value="LogIn"/>
</fieldset>
}
</div>
</body>
</form>
}

please DEBUG your code.
past this code below, just above if(!ModelState.IsValid)
var propertiesWithErrors = ModelState.Where(state => state.Value.Errors.Any()).Select(state => state.Key);;
propertiesWithErrors will give you the list of properties that has validation errors.

Related

Fluent Validation: How to check if the email already exists

I'm working on a Blazor application with fluent validation.
I'm working on a manage profile page where they can change their first name, last name, and email.
Here is my Razor:
<EditForm Model="Input" OnValidSubmit="#UpdateProfile">
<FluentValidator TValidator="InputModelValidator" />
<div class="form-row">
<div class="form-group col-md-6">
<h2>Manage Profile</h2>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<SfTextBox FloatLabelType="FloatLabelType.Auto" Placeholder="First Name" #bind-Value="Input.FirstName"></SfTextBox>
</div>
<div class="form-group col-md-4">
<SfTextBox FloatLabelType="FloatLabelType.Auto" Placeholder="Last Name" #bind-Value="Input.LastName"></SfTextBox>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<SfTextBox FloatLabelType="FloatLabelType.Auto" Placeholder="Email Address" #bind-Value="Input.Email"></SfTextBox>
</div>
</div>
<div class="form-row btn-update">
<div class="form-group col-md-4">
<SfButton IsPrimary="true">Update</SfButton>
<SfToast ID="toast_customDupemail" #ref="#toastDuplicateEmail" Title="Invalid Email" Content="#toastDupEmailErrorMsg" CssClass="e-toast-danger" Timeout=6000>
<ToastPosition X="Center" Y="Top"></ToastPosition>
</SfToast>
</div>
</div>
</EditForm>
Here is my validator:
public class InputModelValidator : AbstractValidator<InputModel>
{
public InputModelValidator()
{
RuleFor(e => e.FirstName).NotEmpty().WithMessage("First name is required.");
RuleFor(e => e.LastName).NotEmpty().WithMessage("Last name is required.");
RuleFor(e => e.Email).NotEmpty().WithMessage("Email is required.");
RuleFor(e => e.Email).EmailAddress().WithMessage("Email is not valid.");
RuleFor(x => x.Email).Custom((email, context) => {
if (IsEmailValid(email) == false)
{
context.AddFailure("The email is not valid.");
}
});
}
private bool IsEmailValid(string email)
{
var userInfo = Task.Run(async () => await utilities.GetApplicationUser().ConfigureAwait(false)).Result;
if (string.Equals(userInfo.Email, email, StringComparison.OrdinalIgnoreCase) == true)
{
return true;
}
return false;
}
}
I have the initial checks for empty, and valid email and such. Those work great!
I need to add a custom message to make sure the email is not already in use.
What is the proper way to talk to the database / asp.net identity UserManager within the validator class?
I'm tried to inject my dependencies, but they are coming in null when I try that.
Thanks.
UPDATE:
Per response that this needs to happen in the handler, is something like this possible?
public partial class ManageProfile
{
public InputModel Input { get; set; } = new InputModel();
private EditContext _editContext;
protected override async Task OnInitializedAsync() // = On Page Load
{
var userInfo = await utilities.GetApplicationUser().ConfigureAwait(false);
Input = new InputModel
{
FirstName = userInfo.FirstName,
LastName = userInfo.LastName,
Email = userInfo.Email
};
await InvokeAsync(StateHasChanged).ConfigureAwait(false);
}
private async Task<EditContext> UpdateProfile()
{
_editContext = new EditContext(Input);
var messages = new ValidationMessageStore(_editContext);
messages.Clear();
if (IsEmailValid(Input.Email) == false)
{
messages.Add(() => Input.Email, "Name should start with a capital.");
_editContext.NotifyValidationStateChanged();
return _editContext;
}
return _editContext;
}
private void ValidateFields(EditContext editContext, ValidationMessageStore messages, FieldIdentifier field)
{
messages.Clear();
if (IsEmailValid(Input.Email) == false)
{
messages.Add(() => Input.Email, "Name should start with a capital.");
editContext.NotifyValidationStateChanged();
}
}
private bool IsEmailValid(string email)
{
var userInfo = Task.Run(async () => await utilities.GetApplicationUser().ConfigureAwait(false)).Result;
if (string.Equals(userInfo.Email, email, StringComparison.OrdinalIgnoreCase) == true)
{
return true;
}
return false;
}
}
public class InputModel
{
[Required]
[MaxLength(250)]
[Display(Name = "First Name", Prompt = "Enter first name")]
public string FirstName { get; set; }
[Required]
[MaxLength(250)]
[Display(Name = "Last Name", Prompt = "Enter last name")]
public string LastName { get; set; }
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[Required]
[EmailAddress]
[Display(Name = "Email", Prompt = "Enter email")]
public string Email { get; set; }
}
public class InputModelValidator : AbstractValidator<InputModel>
{
public InputModelValidator()
{
RuleFor(e => e.FirstName).NotEmpty().WithMessage("First name is required.");
RuleFor(e => e.LastName).NotEmpty().WithMessage("Last name is required.");
RuleFor(e => e.Email).NotEmpty().WithMessage("Email is required.");
RuleFor(e => e.Email).EmailAddress().WithMessage("Email is not valid.");
}
}
UPDATE 3:
public class InputModelValidator : AbstractValidator<InputModel>
{
public InputModelValidator(UserManager<ApplicationUser> user)
{
RuleFor(e => e.FirstName).NotEmpty().WithMessage("First name is required.");
RuleFor(e => e.LastName).NotEmpty().WithMessage("Last name is required.");
RuleFor(e => e.Email).NotEmpty().WithMessage("Email is required.");
RuleFor(e => e.Email).EmailAddress().WithMessage("Email is not valid.");
//RuleFor(e => e.Email).EmailAddress().WithMessage("Email is not valid.").Must(IsEmailexist).WithMessage("{PropertyName} Is Already Exist.");
}
private async Task<bool> IsEmailexist(string Email)
{
return false;
}
}
I tried injecting UserManager<>, but I have this error:
Severity Code Description Project File Line Suppression State
Error CS0310 'InputModelValidator' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TValidator' in the generic type or method 'FluentValidator' C:...\Microsoft.NET.Sdk.Razor.SourceGenerators\Microsoft.NET.Sdk.Razor.SourceGenerators.RazorSourceGenerator\Areas_Identity_Pages_Account_ManageProfile_razor.g.cs 200 Active
checking for duplication is not property or value validation, it's better to check this validation in handler or control-action
checking email already exist in DB in middleware follow below process
public class InputModelValidator : AbstractValidator<InputModel>
{
private EditContext _editContext;
public InputModelValidator(EditContext editContext)
{
_editContext=editContext;
RuleFor(e => e.FirstName).NotEmpty().WithMessage("First name is required.");
RuleFor(e => e.LastName).NotEmpty().WithMessage("Last name is required.");
RuleFor(e => e.Email).NotEmpty().WithMessage("Email is required.");
RuleFor(e => e.Email).EmailAddress().WithMessage("Email is not valid.").Must(IsEmailexist).WithMessage("{PropertyName} Is Already Exist.");;
}
private bool IsEmailexist(string Email)
{
return _editContext.userInfo.where(em=>em.EmailId==Email).FirstOrDefault()!=null?true:false;
}
}
Please refer to this answer: https://stackoverflow.com/a/72848675/9594249
Summary: I needed to make a custom form validation that was seperate from FluentValidation.
<EditForm Model="#Input" OnValidSubmit="#UpdateProfile">
<FluentValidator TValidator="InputModelValidator" />
<UI.Models.Other.CustomFormValidator #ref="#customFormValidator" />
https://www.syncfusion.com/blogs/post/blazor-forms-and-form-validation.aspx

ASP.Net MVC - cannot set value of #Html.Checkbox after changing dropdownlist

I've looking all over for something similar, couldn't find nothing..
I'm using ASP.NET MVC 4. I'm building a page so the users in my app can manage the permissions associated with each role.
So i have a view with #htmlDropDownList to show all the available roles, and below, one #Html.CheckBox for each Permission of the role wich is selected above.
The first time the view is rendered, the checkboxes are all set to true or false, according to the permission of that role.All is fine, life is good :) . When the value of the drop is changed, i post the SelectedRoleId using $.ajax. Then, i fetch all the permissions of the new selected role.
While in debug, in the razor view, i can confirm the new values (true or false) inside the model are correct. The problem is that the checkboxes show the old values, before the role was changed..
This is my first question asked, so i'll have to apologize if the question is not being made the best way.
And thx in advance to all of you :)
So here's my Controller:
public ActionResult Index(int ? SelectedRoleId)
{
ManagePermissionsViewModel model = new ManagePermissionsViewModel();
if (SelectedRoleId == null)
{
model.SelectedRoleID = 1; // value 1 is the supervisor Role
}
else
{
model.SelectedRoleID = SelectedRoleId;
}
//values for the dropdownlist of Roles
var items = from x in db.UserRoles
select x;
model.RoleList = new SelectList(items, "Id", "DESCRIPTION");
//gets all the permissions of the selected role
model.EntirePermissionList = (from k in db.Permissions
select new Permission
{
IdPermission = k.Id,
PermissionDescription = k.Description,
IsSet = db.RolePermissions.Any(n => n.RoleId == model.SelectedRoleID && n.PermissionId == k.Id),
PermissionGroupId = (int)k.PermissionGroupId
}).ToList();
//Gets all the groups of Permissions
model.ListPermissionGroups = (from l in db.PermissionGroups
select new PermissionGroup
{
Id = l.Id,
Description = l.Description
}).ToList();
return View(model);
}
[HttpPost]
public ActionResult Index(FormCollection form) {
switch (form["SubmitButton"])
{
case "Save":
SavePermissions();
break;
default:
return RedirectToAction("Index", new RouteValueDictionary(new { controller = "ManagePermissions", action = "Index", SelectedRoleId = Convert.ToInt32(form["SelectedRoleId"]) }));
}
return View();
}
And here is my View:
'#model AML.Web.Models.ManagePermissionsViewModel
#using (Html.BeginForm("Index", "ManagePermissions", FormMethod.Post, new { id = "MyForm" }))
{
#Html.Label("Role :", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownList("RoleId", Model.RoleList, new { id = "RoleId" })
<div>
#foreach (var item in Model.ListPermissionGroups)
{
<h3> #item.Description</h3>
foreach (var permission in Model.EntirePermissionList.Where(n => n.PermissionGroupId == item.Id))
{
<h5>
#permission.PermissionDescription
#Html.CheckBox("Chk_Permisssion", permission.IsSet)
</h5>
}
}
</div>
<input type="submit" value="Save" name="SubmitButton" class="btn btn-default" />
}
#section Scripts {
<script type="text/JavaScript">
$(document).ready(function () {
$("#RoleId").change(function (e) {
e.preventDefault();
$.ajax({
url: "/ManagePermissions/Index",
cache: false,
type: "POST",
data: { 'SelectedRoleId': $(this).val() },
dataType: "json",
success: function (result) { console.log("Sucess!"); },
error: function (error) { console.log("Error!"); }
})
});
});
</script>
}
And my viewModel:
public class ManagePermissionsViewModel
{
public int? SelectedRoleID { get; set; }
public string SelectedRoleDescription { get; set; }
public SelectList RoleList { get; set; }
public List<Permission> EntirePermissionList { get; set; }
public List<PermissionGroup> ListPermissionGroups { get; set; }
}
public class Permission
{
public int IdPermission { get; set; }
public bool IsSet { get; set; }
public string PermissionDescription { get; set; }
public int PermissionGroupId { get; set; }
}
public class PermissionGroup {
public int Id { get; set; }
public string Description{ get; set; }
}
UPDATE 1 -
Well, i think i got it. Let me post my approach
In the View:
#Html.DropDownListFor(n => n.SelectedRoleID, Model.RoleList,null,
new { onchange = "document.location.href = '/ManagePermissions/Index?SelectedRoleId=' + this.options[this.selectedIndex].value;" })
<div>
#foreach (var item in Model.ListPermissionGroups)
{
<h3> #item.Description</h3>
foreach (var permission in Model.EntirePermissionList.Where(n => n.PermissionGroupId == item.Id))
{
<h5>
#permission.PermissionDescription
<input type="checkbox" id="#permission.IdPermission" checked="#permission.IsSet">
</h5>
}
}
</div>
And in the Controller:
public ActionResult Index(int? SelectedRoleId)
{
ManagePermissionsViewModel model = new ManagePermissionsViewModel();
ModelState.Clear();
if (SelectedRoleId == null)
{
model.SelectedRoleID = 1;
}
else
{
model.SelectedRoleID = SelectedRoleId;
}
var items = from x in db.UserRoles
select x;
model.RoleList = new SelectList(items, "Id", "DESCRIPTION");
model.EntirePermissionList = (from k in db.Permissions
select new Permission
{
IdPermission = k.Id,
PermissionDescription = k.Description,
IsSet = db.RolePermissions.Any(n => n.RoleId == model.SelectedRoleID && n.PermissionId == k.Id),
PermissionGroupId = (int)k.PermissionGroupId
}).ToList();
model.ListPermissionGroups = (from l in db.PermissionGroups
select new PermissionGroup
{
Id = l.Id,
Description = l.Description
}).ToList();
ModelState.Clear();
return View(model);
}
Now each time the Drop changes value, the permissions in the checkboxes are updated. I got it to work with the attribute on the drop, "on change = Document.location.hef = URL". Is this a good approach? Or should i use something like ajax request ?
UPDATE 2
The Controller:
public async Task<ActionResult> Index(int? SelectedRoleId)
{
if (SelectedRoleId == null)
{
SelectedRoleId = 1;
}
var model = await GetSelectedPermissions(SelectedRoleId);
return this.View("Index",model);
}
[HttpGet]
public async Task<ActionResult> GetPermissions(string Id)
{
var SelectedRoleId = int.Parse(Id);
var model = await this.GetSelectedPermissions(SelectedRoleId);
return PartialView("_ManagePermissions", model);
}
private async Task<ManagePermissionsViewModel> GetSelectedPermissions(int? SelectedRoleId)
{
ModelState.Clear();
ManagePermissionsViewModel model = new ManagePermissionsViewModel();
model.SelectedRoleID = SelectedRoleId;
var items = from x in db.UserRoles
select x;
model.RoleList = new SelectList(items, "Id", "DESCRIPTION");
model.EntirePermissionList = await (from k in db.Permissions
select new Permission
{
IdPermission = k.Id,
PermissionDescription = k.Description,
IsSet = db.RolePermissions.Any(n => n.RoleId == model.SelectedRoleID && n.PermissionId == k.Id),
PermissionGroupId = (int)k.PermissionGroupId
}).ToListAsync();
model.ListPermissionGroups = await (from l in db.PermissionGroups
select new PermissionGroup
{
Id = l.Id,
Description = l.Description
}).ToListAsync();
return model;
}
The View
<h2>Permissions - Ajax with Partial View</h2>
#using (Html.BeginForm("SaveData", "ManagePermissions", FormMethod.Post, new { id = "MyForm" }))
{
#Html.Label("Role :", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(n => n.SelectedRoleID, Model.RoleList, null, null)
<div id="target">
#Html.Partial("~/Views/Shared/_ManagePermissions.cshtml", Model)
</div>
<input type="submit" value="Save" name="SubmitButton" class="btn btn-default" />
}
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$("#SelectedRoleID").change(function () {
var SelectedRoleID = $("#SelectedRoleID").val();
$("#target").load('#(Url.Action("GetPermissions","ManagePermissions",null, Request.Url.Scheme))?Id=' + SelectedRoleID);
});
});
</script>
}
And the Partial View:
<div>
#foreach (var item in Model.ListPermissionGroups)
{
<h3> #item.Description</h3>
foreach (var permission in Model.EntirePermissionList.Where(n => n.PermissionGroupId == item.Id))
{
<h5>
#permission.PermissionDescription
<input type="checkbox" id="#permission.IdPermission" checked="#permission.IsSet">
</h5>
}
}
</div>

MVC 4: Ambiguous request for action

I have the following code:
#using (Html.BeginForm("FolderChange", "EdiSender", FormMethod.Post, new {id = "ediFilesForm"}))
{
var directoriesSelectList = new SelectList(Model.Directories);
#Html.DropDownListFor(m => m.SelectedDirectory, directoriesSelectList, new {#Id = "Directories",
#style = "width:Auto;", #size = 20, onchange = "$('#ediFilesForm').submit()", name = "action:FolderChange"})
var ediFilesSelectList = new SelectList(Model.EdiFileNames);
#Html.DropDownListFor(m => m.SelectedEdiFile, ediFilesSelectList, new {#Id = "EdiFileNames",
#style = "width:Auto;", #size = 20})
}
<br/>
<form action="" method="post">
<input type="submit" value="Send" name="action:Send" />
<input type="submit" value="Delete" name="action:Delete" />
<input type="submit" value="Refresh" name="action:Refresh" />
</form>
Here is a part of the controller:
[HttpPost]
[ActionName("FolderChange")]
public ActionResult FolderChange(EdiFileModel ediFileModel)
{
ediFileModel = Load(ediFileModel.SelectedDirectory);
return View("Index", ediFileModel);
}
...
[HttpPost]
[MultipleButton(Name = "action", Argument = "Send")]
public ActionResult Send(EdiFileModel ediFileModel)
{
....
return View("Index", ediFileModel);
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultipleButtonAttribute : ActionNameSelectorAttribute
{
public string Name { get; set; }
public string Argument { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
var isValidName = false;
var keyValue = string.Format("{0}:{1}", Name, Argument);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
if (value != null)
{
controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
isValidName = true;
}
return isValidName;
}
}
When I press any of the buttons, I get the following message:
The current request for action 'FolderChange' on controller type 'EdiSenderController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Send(EdiSimulatorWebSender.Models.EdiFileModel) on type EdiSimulatorWebSender.Controllers.EdiSenderController
System.Web.Mvc.ActionResult FolderChange(EdiSimulatorWebSender.Models.EdiFileModel) on type EdiSimulatorWebSender.Controllers.EdiSenderController
Could you please help me understand what is wrong with my view?
Thanks.
make sure on your controller you add the post attribute to your post method
public ActionResult FolderChange ... for the get
[HttpPost]
public ActionResult FolderChange... for the post

MVC 4 multiple buttons in form - why isn't this code working

I am trying to use a variation of the code from this page:
Multiple button in MVC
But everytime I click on the buttons it goes to the index actionresult method and not one of the button methods. Index is the view name but the button clicks are happening in a partial view called "P_NewPersonForm.cshtml"
P_NewPersonForm.cshtml
#using (Html.BeginForm())
{
<div id="divClaimType">
#Html.Label("Claim type:")
#Html.DropDownListFor(m => m.modelClaim.ClaimType, new List<SelectListItem>
{
new SelectListItem{ Text="Legal", Value = "Legal" },
new SelectListItem{ Text="Immigration", Value = "Immigration" },
new SelectListItem{ Text="Housing", Value = "Housing" }
})
</div>
<div id="divClaimStatus" style="padding: 5px;">
#foreach(var item in Model.LinkerStatusOfClaim)
{
#Html.Label("Claim status:")
#Html.DropDownListFor(m => m.LinkerStatusOfClaim[0].ClaimStatusID, new SelectList(Model.modelClaimStatus, "ClaimStatusID", "ClaimStatus"))
#Html.LabelFor(m => m.LinkerStatusOfClaim[0].Notes)
#Html.TextAreaFor(m => m.LinkerStatusOfClaim[0].Notes)
#Html.LabelFor(m => m.LinkerStatusOfClaim[0].StartDate)
#Html.TextBoxFor(m => m.LinkerStatusOfClaim[0].StartDate, new { #id = "datepicker", #Value = DateTime.Now, #readonly = true, Style = "background:#cccccc;" })
<br />
#Html.ValidationMessageFor(model => model.LinkerStatusOfClaim[0].StartDate)
<br />
}
<input type="submit" value="Add another status to this claim..." name="action:add"/>
<input type="submit" value="Delete status." name="action:remove"/>
#* #Ajax.ActionLink("Add another status to this claim...", "AddClaim", "Client", new AjaxOptions { HttpMethod = "POST"})*#
</div>
}
</div>
I have one button for adding to the collection of claims and another to remove one from the collection.
ClientController
public ActionResult Index()
{
var Model = new modelPersonClaim();
// Add one item to model collection by default
LinkerStatusOfClaim LinkerStatusOfClaim = new LinkerStatusOfClaim();
Model.LinkerStatusOfClaim.Add(LinkerStatusOfClaim);
DataLayer.RepositoryClient RC = new RepositoryClient();
Model.isValidModel = true;
RC.GetClaimTypes(Model, PersonTypes.NewPerson.ToString());
return View(Model);
}
[HttpPost]
public ActionResult P_NewPersonForm(modelPersonClaim Model)
{
DataLayer.RepositoryClient RC = new RepositoryClient();
RC.GetClaimTypes(Model, PersonTypes.NewPerson.ToString());
Model.isValidModel = ModelState.IsValid;
if (ModelState.IsValid)
{
RC.CreatePerson(Model);
Model.SuccessfulInsert = true;
Model.InsertString = "Person data has been successfully inserted into the database.";
if (Model.modelClaim.ClaimMade)
{
RC.CreateClaim(Model);
}
}
else
{
Model.SuccessfulInsert = false;
Model.InsertString = "Person data could not be inserted into the database. Missing key fields.";
}
return View("Index", Model);
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
public string Name { get; set; }
public string Argument { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
var isValidName = false;
var keyValue = string.Format("{0}:{1}", Name, Argument);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
if (value != null)
{
controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
isValidName = true;
}
return isValidName;
}
}
[HttpPost]
[MultiButtonAttribute(Name = "action", Argument = "Add another status to this claim...")]
public ActionResult AddClaimStatus(modelPersonClaim Model)
{
Model.LinkerStatusOfClaim.Insert(Model.LinkerStatusOfClaim.Count, new LinkerStatusOfClaim());
return View("Index", Model);
}
[HttpPost]
[MultiButtonAttribute(Name = "action", Argument = "Delete status.")]
public ActionResult RemoveClaimStatus(modelPersonClaim Model)
{
// Can't remove IF only 1
if (Model.LinkerStatusOfClaim.Count == 1)
{
}
else
{
Model.LinkerStatusOfClaim.RemoveAt(Model.LinkerStatusOfClaim.Count);
}
return View("Index", Model);
}
When I click one the buttons it hits the public override bool IsValidName twice. Once for each button. But then because the action name is always index, it goes to the index method and not one of the button methods.
Does anyone have any ideas how to fix this?
Something is wrong with this part:
var keyValue = string.Format("{0}:{1}", Name, Argument);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
Your attribute is this:
[MultiButtonAttribute(Name = "action", Argument = "Add another status to this claim...")]
So in that case keyValue will become: "action:Add another status to this claim..." while your HTML states: <input type="submit" value="Add another status to this claim..." name="action:add"/>, so I think Argument in your attribute should be add.

Multiple models in view error

I have a view pages that have different partial views with different models. I created a model class that will call other classes so i can use it on the main view page. But my problem is that when i try to change the password it gives me an error that i am passing in a model which i need to pass in another model. I believe i have my structure right but not sure what is causing this issue.
Main view:
#model Acatar.Models.ProfileModel
#{
ViewBag.Title = "ProfileAccount";
}
#{ Html.RenderAction("_PlayNamePartial"); }
#{ Html.RenderAction("_UsernamePartial", "Account");}
#{ Html.RenderAction("_TalentsPartial", "Account");}
#if (ViewBag.HasLocalPassword)
{
#Html.Partial("_ChangePasswordPartial")
}
else
{
#Html.Partial("_SetPasswordPartial")
}
Profile Model: containing models that i have created
public class ProfileModel
{
public LocalPasswordModel LocalPasswordModel { get; set; }
public PlayNameModel PlayNameModel { get; set; }
public UsernameModel UsernameModel { get; set; }
public TalentsModel TalentsModel { get; set; }
}
Controller:
public ActionResult Profile(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: "";
ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.ReturnUrl = Url.Action("Profile");
return View();
}
POST:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Profile(LocalPasswordModel model)
{
bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.HasLocalPassword = hasLocalAccount;
ViewBag.ReturnUrl = Url.Action("Profile");
if (hasLocalAccount)
{
if (ModelState.IsValid)
{
// ChangePassword will throw an exception rather than return false in certain failure scenarios.
bool changePasswordSucceeded;
try
{
changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
}
catch (Exception)
{
changePasswordSucceeded = false;
}
if (changePasswordSucceeded)
{
return RedirectToAction("Profile", new { Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
}
else
{
// User does not have a local password so remove any validation errors caused by a missing
// OldPassword field
ModelState state = ModelState["OldPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
try
{
WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
return RedirectToAction("Profile", new { Message = ManageMessageId.SetPasswordSuccess });
}
catch (Exception e)
{
ModelState.AddModelError("", e);
}
}
}
return View(model);
}
View Page for password change:
#model Project.Models.LocalPasswordModel
#using (Html.BeginForm("Profile", "Account")) {
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<fieldset>
<legend>Change Password Form</legend>
#Html.LabelFor(m => m.OldPassword)
#Html.PasswordFor(m => m.OldPassword)
#Html.LabelFor(m => m.NewPassword)
#Html.PasswordFor(m => m.NewPassword)
#Html.LabelFor(m => m.ConfirmPassword)
#Html.PasswordFor(m => m.ConfirmPassword)
<br/>
<input class="btn btn-small" type="submit" value="Change password" />
</fieldset>
The Error i am getting:
The model item passed into the dictionary is of type 'Project.Models.LocalPasswordModel', but this dictionary requires a model item of type 'Project.Models.ProfileModel'.
Try specifying model in #Html.Partial method. (Excuse my syntax, I dont have an IDE now)
#if (ViewBag.HasLocalPassword)
{
#Html.Partial("_ChangePasswordPartial",Model.LocalPasswordModel)
}
else
{
#Html.Partial("_SetPasswordPartial",Model.LocalPasswordModel)
}
(I guess second view also use same model)
But I couldn't see any model passed into your view from your controller, You should pass an model to view
public ActionResult Profile(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: "";
ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.ReturnUrl = Url.Action("Profile");
var ProfileModel = new ProfileModel();
ProfileModel.LocalPasswordModel = populateFromDB();
return View(ProfileModel);
}
or consider creating an action result to Render this partial view as you have done for other partial views like this.(If there are no other intentions using Html.partial here)
#if (ViewBag.HasLocalPassword)
{
#Html.RenderAction("_ChangePasswordPartial")
}
else
{
#Html.RenderAction("_SetPasswordPartial")
}