Based on this post
Second answerI tried to create a dropdown list for my register page.
Register page has a field where you can select the PossibleAccessRight for the user while registering him/her which should be saves in AccessRight Attribute.
Right now i can't even show the items in dropdownlist
My model looks like this
public class UserModel
{
public int UserId { get; set; }
[Required]
[EmailAddress]
[StringLength(100)]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email ID ")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(20,MinimumLength = 6)]
[Display(Name = "Password ")]
public string Password { get; set; }
[Required]
[Display(Name = "First Name ")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name ")]
public string LastName { get; set; }
[Required]
[Display(Name = "Address ")]
public string Address { get; set; }
public List<string> PossibleRights;
[Required]
[Display(Name = "Access Rights")]
public string AccessRight { get; set; }
public UserModel()
{
PossibleRights = new List<string>()
{
{"High"},
{"Low"},
};
}
}
in controller i have this in registeration method which is httppost method
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(Models.UserModel user)
{
var rights = new UserModel();
if (ModelState.IsValid)
{
using (var db = new DBaseEntities())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(user.Password);
var sysUser = db.SystemUsers.Create();
sysUser.FirstName = user.FirstName;
sysUser.Email = user.Email;
sysUser.Password = encrpPass;
sysUser.PasswordSalt = crypto.Salt;
db.SystemUsers.Add(sysUser);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("","Login data is incorrect.");
}
return View(rights);
}
View for this method looks like this
<div class="editor-label">#Html.LabelFor(u=> u.FirstName)</div>
<div class="editor-field"> #Html.TextBoxFor(u=> u.FirstName)</div>
<br/>
<div class="editor-label">#Html.LabelFor(u=> u.LastName)</div>
<div class="editor-field"> #Html.TextBoxFor(u=> u.LastName)</div>
<br/>
<div class="editor-label">#Html.LabelFor(u=> u.Address)</div>
<div class="editor-field"> #Html.TextBoxFor(u=> u.Address)</div>
<br/>
<div class="editor-label">#Html.LabelFor(u=> u.Email)</div>
<div class="editor-field"> #Html.TextBoxFor(u=> u.Email)</div>
<br/>
<div class="editor-label">#Html.LabelFor(u=> u.Password)</div>
<div class="editor-field"> #Html.PasswordFor(u=> u.Password)</div>
<br/>
<div class="editor-label">#Html.LabelFor(u=> u.AccessRight)</div>
<div class="editor-field"> #Html.DropDownListFor(u=> u.PossibleRights, new SelectList(Model.PossibleRights))</div>//error at this line(NullReference exception)
<br/>
<input type="submit" value="Register"/>
any idea what I'm doing wrong? Also, is my approach to show the items in dropdownlist good? Can you suggest better idea if any?
If you want to display any info on the view, you have to provide this info to the view first. Right now this code:
public ActionResult Register()
{
return View();
}
does not provide any info at all. Model for the view is created with default constructor, which means that model object is empty, therefore nothing is displayed on the view (particularly in the dropdown list). What you need is some initialization like this:
public ActionResult Register()
{
UserModel model = new UserModel();
model.PossibleRights = new List<string>{"Right1", "Right2", "Right3"};
// or go to db, or whatever
return View(model);
}
Besides dropdown returns selected value when posted, which is string representing a right in this case. So you need to introduce some field in the model to store the selection:
public class UserModel
{
...
public List<string> PossibleRights;
public string SelectedRight;
...
}
Usage on view is the following:
#Html.DropDownListFor(u => u.SelectedRight, new SelectList(Model.PossibleRights))
Related
My Code is as shown in below
MODEL
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyProject.Models
{
[Table("UserMaster")]
public partial class UserMaster
{
[Key]
public int UserID { get; set; }
[System.Web.Mvc.Remote("doesAlreadyExist", "User", HttpMethod = "POST", ErrorMessage = "User Number already exists. Please enter a different Number.")]
[Required(ErrorMessage = "Enter Personal No")]
[Display(Name = "User No")]
[StringLength(10)]
public string User No{ get; set; }
[Required(ErrorMessage = "Enter Password")]
[Display(Name = "Password")]
public string Password { get; set; }
[NotMapped]
[Compare("Password", ErrorMessage = "Password doesn't match.")]
[Display(Name = "Confirm Password")]
public string CPassword { get; set; }
}
public class UserChangePassMV
{
[Required]
[Display(Name = "Old Password")]
[DataType(DataType.Password)]
public string OldPassword { get; set; }
[Required]
[Display(Name = "New Password")]
[DataType(DataType.Password)]
public string NewPassword { get; set; }
[NotMapped]
[Display(Name = "Confirm Password")]
[DataType(DataType.Password)]
[Compare("NewPassword",ErrorMessage="Password Doesnt Match in User Change Password.")]
public string ConfirmPassword { get; set; }
}
public class ChangeAvatar
{
public byte[] Photo { get; set; }
public string ImgSrc { get; set; }
}
}
CONROLLER
[OutputCache(Duration = 10, VaryByParam = "none", Location = OutputCacheLocation.Client, NoStore = true)]
public ActionResult ChangeAvatar()
{
ChangeAvatar avatar = new Models.ChangeAvatar();
int uid = Convert.ToInt32(Session.GetDataFromSession<CommonUserSession>("CommonUserSession").UserID);
avatar.Photo = db.UserMasters.SingleOrDefault(x => x.UserID == uid).Photo;
if (avatar.Photo != null)
{
string imageBase64 = Convert.ToBase64String(avatar.Photo);
avatar.ImgSrc = string.Format("data:image/jpeg;base64,{0}", imageBase64);
}
return View("ChangeAvatar", "_Layout", avatar);
}
[HttpPost]
public ActionResult ChangeAvatar(HttpPostedFileBase file)
{
if (file == null)
{
ModelState.AddModelError("", "Select image to upload");
}
int uid = Convert.ToInt32(Session.GetDataFromSession<CommonUserSession>("CommonUserSession").UserID);
UserMaster Mem = db.UserMasters.SingleOrDefault(x => x.UserID == uid);
try
{
if (ModelState.IsValid)
{
string path = System.IO.Path.Combine(Server.MapPath("~/ProfileImg"), uid.ToString() + ".jpg");
// file is uploaded
file.SaveAs(path);
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
Mem.Photo = array;
}
db.SaveChanges();
return RedirectToAction("ChangeAvatar");
}
}
catch (DbEntityValidationException ex)
{
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
var fullErrorMessage = string.Join("; ", errorMessages);
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
HtmlHelperExtensions.LogError(ex);
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
catch (RetryLimitExceededException /* dex */)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
ChangeAvatar avatar = new Models.ChangeAvatar();
avatar.Photo = db.UserMasters.SingleOrDefault(x => x.UserID == uid).Photo;
if (avatar.Photo != null)
{
string imageBase64 = Convert.ToBase64String(avatar.Photo);
avatar.ImgSrc = string.Format("data:image/jpeg;base64,{0}", imageBase64);
}
return View(avatar);
}
VIEW
#model MyProject.Models.ChangeAvatar
#{
ViewBag.Title = "Change Avatar";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!-- BEGIN PAGE BAR -->
#section PageBreadcrumb{
<ul class="breadcrumb">
<li><i class="icon-home2 position-left"></i> Dashboard</li>
<li class="active">Change Avatar</li>
</ul>
}
<!-- END PAGE BAR -->
<div class="clearfix"></div>
#section PageJS{
<script type="text/javascript" src="~/assets/js/plugins/uploaders/fileinput.min.js"></script>
<script type="text/javascript" src="~/assets/js/pages/uploader_bootstrap.js"></script>
<script type="text/javascript">
if ('#ViewBag.Status' != "") {
var notice = new PNotify({
title: '#ViewBag.Status',
text: '#ViewBag.Msg',
addclass: 'bg-#ViewBag.Type' //primary,info,danger,success,warning
}).get().click(function () {
notice.remove(); //Click to remove
});
}
</script>
}
#using (Html.BeginForm("ChangeAvatar", "User", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="panel panel-flat">
<div class="panel-heading">
<h5 class="panel-title text-primary">Change Avatar</h5>
<div class="heading-elements">
<ul class="icons-list">
<li><a data-action="collapse"></a></li>
#*<li><a data-action="reload"></a></li>
<li><a data-action="close"></a></li>*#
</ul>
</div>
</div>
<div class="panel-body">
<div class="col-md-12">
<div class="form-group">
<label class="col-lg-2 control-label text-semibold">Avatar:</label>
<div class="col-lg-10">
<input type="file" name="file" class="file-input-custom" data-show-caption="true" data-show-upload="true" accept="image/*">
<span class="help-block">Show only image files for selection & preview.</span>
</div>
</div>
<div class="col-lg-12">
<div class="text-right">
<p>
<div class="text-right">
#*<button type="submit" class="btn btn-primary">Change <i class="icon-arrow-right14 position-right"></i></button>*#
</div>
</p>
</div>
</div>
</div>
</div>
</div>
}
Now while I am trying to save the data in Change Avatar it shows error of first model for
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. The validation errors are: Password doesn't match.
If i remove Compare part than it works, but i need that compare to confirm password
is this possible to work with two class like this?
Help me out I am stuck here.
Your UserMaster class has a CPassword property which will be set to null when you do db.UserMasters.SingleOrDefault(x => x.UserID == uid). You update Photo field and save the entity. db.SaveChanges(); triggers validation on your entity which is comparing password field values producing the exception. Both MVC and EF use data annotation attributes for validation. EF reads an attribute designed for presentation layer.
Think why do you need a CPassword field in your model class? It is not stored in the database. It is needed only to capture user input. Usually this is so-called viewModel class responsibility. In order to resolve the issue split UserMaster into separate classes.
public partial class UserMaster
{
[Key]
public int UserID { get; set; }
[Required]
[Display]
[StringLength(10)]
public string UserNo { get; set; }
[Required]
public string Password { get; set; }
}
public class UserMasterViewModel
{
public int UserID { get; set; }
[System.Web.Mvc.Remote("doesAlreadyExist", "User", HttpMethod = "POST", ErrorMessage = "User Number already exists. Please enter a different Number.")]
[Required(ErrorMessage = "Enter Personal No")]
[Display(Name = "User No")]
[StringLength(10)]
public string UserNo{ get; set; }
[Required(ErrorMessage = "Enter Password")]
[Display(Name = "Password")]
public string Password { get; set; }
[Compare("Password", ErrorMessage = "Password doesn't match.")]
[Display(Name = "Confirm Password")]
public string CPassword { get; set; }
}
Use UserMasterViewModel as a #model of your views. Perform dbModel <=> viewModel mappings in you controller methods.
I initially set up my dropdown with submit button which was fine but now I wanted to have it just work without the button (I added onchange). However now I find another difficulty that initially when page is displayed, if I "select" the first option, nothing happens (obviously) so I though to add "please select" option. I found couple of solutions such as writing my custom list of SelectListOptions but this seems like it could be over the top for my case. Could anyone shed some light here and let me know what would be the easiest option here? Sorry if it is simple answer I am really stuck. Here is my code:
Model
public class SurveyDropdownModel
{
public SelectList selectSurveys { get; set; }
public string selectedId { get; set; }
public IEnumerable<RespondentModel> respondents { get; set; }
public SurveyDropdownModel(List<SurveyModel> surveys)
{
selectSurveys = new SelectList(surveys, "SurveyID", "SurveyTitle");
respondents = null;
}
}
public class SurveyModel
{
[Required]
[Display(Name = "Survey ID")]
public int SurveyID { get; set; }
[Display(Name = "Title")]
public string SurveyTitle { get; set; }
[Display(Name = "Updated")]
public DateTime SurveyUpdatedDate { get; set; }
[Display(Name = "Active")]
bool IsActive { get; set; }
}
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
HealthCheckDataLayer.HealthCheckRepository repo = new HealthCheckRepository(connectionString);
List<SurveyModel> surveyList = repo.ReturnSurveys<SurveyModel>();
var model = new SurveyDropdownModel(surveyList);
return View(model);
}
[HttpPost]
public ActionResult Index(SurveyDropdownModel model)
{
//not important here
}
}
View
#model HealthCheckWebApp.Models.SurveyDropdownModel
#{
ViewBag.Title = "Home Page";
}
<div class="row">
<div class="col-md-4">
<h4>Select product:</h4>
#using (Html.BeginForm("Index", "Home"))
{
#Html.DropDownList("selectedId", Model.selectSurveys, new { onchange = "this.form.submit()" })
}
</div>
</div>
<br />
<br />
#if(Model.respondents!=null)
{
#* not relevant here*#
}
I guess now that I didn't include how do I pull my list , I am calling a stored procedure from my repository there (It's required to do it with SP).
Thanks.
Use #Html.DropDownListFor. Here is a description.
Usage:
#Html.DropDownListFor(x=> x.selectedId, Model.selectSurveys, "Select something", new { onchange = "this.form.submit()" )
I am not able to save the record after implementing the drop down field. Can someone please correct my code.
Create.cshtml
#model SomeIndianShit.Models.Accommodation
#{
ViewBag.Title = "Advertise Accommodation";
}
<form name="datapluspics" method="post" enctype="multipart/form-data">
#Html.ValidationSummary(true)
<fieldset>
<legend>Accommodation</legend>
<div class="editor-label">
#Html.LabelFor(model => model.State)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.SelectedAustraliaStateId, Model.AustraliaStates)
</div>
<p>
<input type="submit" value=" Save " />
</p>
</fieldset>
</form>
My Model:
public class AustraliaStates
{
[Key]
public string AustraliaStateId { get; set; }
public string AustraliaStateName { get; set; }
}
public class Accommodation
{
[Key]
public string A_Unique_Id { get; set; }
[Display(Name = "Ad Id")]
public string Ad_Id { get; set; }
[Display(Name = "Posted By")]
public string User { get; set; }
[Display(Name = "Street")]
public string Street { get; set; }
[Required]
[Display(Name = "Suburb")]
public string Suburb { get; set; }
[Required]
[Display(Name = "State")]
public string State { get; set; }
public byte[] Picture1 { get; set; }
public string SelectedAustraliaStateId { get; set; }
public IEnumerable<SelectListItem> AustraliaStates { get; set; }
}
AccommodationController.cs
// GET: /Accommodation/Create
[Authorize]
public ActionResult Create()
{
var model = new Accommodation
{
AustraliaStates = db.AustraliaStates
.ToList()
.Select(x => new SelectListItem
{
Text = x.AustraliaStateName,
Value = x.AustraliaStateId
})
};
return View(model);
}
/ POST: /Accommodation/Create
[Authorize]
[HttpPost]
public ActionResult Create(Accommodation accommodation, HttpPostedFileBase file1, HttpPostedFileBase file2, HttpPostedFileBase file3)
{
if (ModelState.IsValid)
{
// save and redirect
// ...blah blah...
//blah blah...
db.Accommodation.Add(accommodation);
//Save in Database
db.SaveChanges();
return RedirectToAction("Index");
}
// repopulate SelectList properties [I THINK THIS IS WRONG]
var model = new Accommodation
{
AustraliaStates = db.AustraliaStates
.ToList()
.Select(x => new SelectListItem
{
Text = x.AustraliaStateName,
Value = x.AustraliaStateId
})
};
return View(accommodation);
}
After filling the form, when save button is clicked, the following error message is displayed
The ViewData item that has the key 'SelectedAustraliaStateId' is of type 'System.String' but must be of type 'IEnumerable'.
In your HttpPost controller action you need to repopulate the correct property on the model that you are passing to the view, i.e. set the AustraliaStates on your model the same way you are doing in your GET action:
accommodation.AustraliaStates = db.AustraliaStates
.ToList()
.Select(x => new SelectListItem
{
Text = x.AustraliaStateName,
Value = x.AustraliaStateId
});
return View(accommodation);
Although this error is very common in the forum, but i am not able to understand how to fix it in my project. I am new to MVC framework.
View code:-
#model ClassifiedProject.Models.CreateAdvertVM
<div class="editor-label">#Html.LabelFor(model => model.AdvTitle) <i>(E.g. Old Samsung Galaxy Tab 2)</i></div>
<div class="editor-field">
#Html.EditorFor(model => model.AdvTitle)
#Html.ValidationMessageFor(model => model.AdvTitle)
</div>
<div class="editor-label">#Html.LabelFor(model => model.AdvDescription)</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.AdvDescription)
#Html.ValidationMessageFor(model => model.AdvDescription)
</div>
<div class="editor-label">#Html.Label("Advertisement Category")</div>
<div class="editor-label">
#Html.DropDownListFor(model => model.SelectedCategoryId, Model.Categories, new { #class = "ddlcs" })
#Html.ValidationMessageFor(model => model.SelectedCategoryId)
</div>
<p><input type="submit" value="Save" /></p>
Controller code of Save button actionresult:-
[HttpPost]
public ActionResult Create(TR_ADVERTISEMENT tr_advert)
{
if (ModelState.IsValid)
{
tr_advert.CreatedDate = tr_advert.ModifiedDate = DateTime.Now;
if (tr_advert.IsPriceOnRequest)
{
tr_advert.CurrencyID = 0;
tr_advert.Price = 0;
}
db.ADVERTISEMENT.Add(tr_advert);
db.SaveChanges();
return RedirectToAction("Index");
}
Controller code for the form in render stage:-
// GET: /Advert/Create
public ActionResult Create()
{
var model = new CreateAdvertVM();
ViewBag.Message = "Post New Advertisement.";
////Render Category DDL
var cat = from s in db.CategoryDbSet
where s.IsActive == true
orderby s.CatName
select new { s.CatID, s.CatName };
var catListItems = cat.ToList().Select(c => new SelectListItem
{
Text = c.CatName,
Value = c.CatID.ToString()
}).ToList();
catListItems.Insert(0, new SelectListItem { Text = "[--Select the category--]", Value = "" });
model.Categories = catListItems;
return View(model);
ViewModel inherited from EF class:-
[NotMapped]
public class CreateAdvertVM : TR_ADVERTISEMENT
{
[DisplayName("Category")]
[Required]
public int? SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
EF Model:-
public class TR_ADVERTISEMENT
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AdvID { get; set; }
[Required]
[DisplayName("Sub Category")]
public int SubCatID { get; set; }
public int CurrencyID { get; set; }
[DisplayName("Price on request")]
public bool IsPriceOnRequest { get; set; }
[DisplayName("Posted Date")]
[DisplayFormat (DataFormatString="{0:dd-MM-yyyy}")]
public Nullable<System.DateTime> CreatedDate { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
}
On the save button click, i have to save the data into the tr_advertisement table using the EF model.
Please suggest the solution to this problem.
It is the model type you are passing into your Create ActionMethod.
public ActionResult Create(TR_ADVERTISEMENT tr_advert)
should be
public ActionResult Create(CreateAdvertVM tr_advert)
I am assuming that if your model is not valid, you are passing it back further down in your action result (which you are not showing), such as
Return View(tr_advert)
But, you are passing the wrong model type at that point for that view.
EDIT
I would also update your view model so that instead of inheriting from the EF class, simply include the EF class as a property.
public class CreateAdvertVM
{
[DisplayName("Category")]
[Required]
public int? SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
public TR_ADVERTISEMENT tr_advert{get;set;}
}
This will make it so that your save code in the Create method can still be used with only minor modifications
[HttpPost]
public ActionResult Create(CreateAdvertVM model)
{
if (ModelState.IsValid)
{
model.tr_advert.CreatedDate = model.tr_advert.ModifiedDate = DateTime.Now;
if (model.tr_advert.IsPriceOnRequest)
{
model.tr_advert.CurrencyID = 0;
model.tr_advert.Price = 0;
}
db.ADVERTISEMENT.Add(model.tr_advert);
db.SaveChanges();
return RedirectToAction("Index");
}
My problem is that my ViewModel property doesn't bind into an action parameter.
I think it'll be more clear if i just give you my code.
I have a model as follows:
namespace Sima3.Models
{
using System;
using System.Collections.Generic;
public partial class Usuario
{
public string Login { get; set; }
public string NombreCompleto { get; set; }
public short Organigrama { get; set; }
public int Interno { get; set; }
public string EMail { get; set; }
}
}
And i added DataAnnotations to this partial class in another file (Because this model was generated automatically by EntityFramework), note the remote validation on Login property:
namespace Sima3.Models
{
[MetadataType(typeof(UsuarioMetaData))]
public partial class Usuario
{
}
public class UsuarioMetaData
{
[Display(Name = "Nombre de Usuario")]
[Remote("NoExisteUsuario", "Validation")]
[Required]
public string Login { get; set; }
[Display(Name = "Nombre y Apellido")]
[Required]
public string NombreCompleto { get; set; }
[Display(Name = "Sector")]
[Required]
public short Organigrama { get; set; }
[Required]
public int Interno { get; set; }
[EmailAddress]
[Required]
public string EMail { get; set; }
}
}
Now, i have a ViewModel wich contains a property of type Usuario and some other stuff needed to render my View:
namespace Sima3.ViewModels.PedidoViewModels
{
public class AgregarViewModel
{
public Usuario Usuario { get; set; }
public Pedido Pedido { get; set; }
public SelectList ListaSectores { get; set; }
public SelectList ListaEstados { get; set; }
public SelectList ListaPrioridades { get; set; }
public SelectList ListaTipos { get; set; }
public SelectList ListaDirecciones { get; set; }
}
}
And my view looks as follows (I'll only post part of it, if u need to see more let me know):
#using (Ajax.BeginForm("Crear", "Usuario", null,
new AjaxOptions
{
OnSuccess = "UsuarioCreadoSuccess",
HttpMethod = "Post"
}
, new { #class = "form-horizontal", id = "FormUsuario" }))
{
#Html.AntiForgeryToken()
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title title">Nuevo Usuario</h4>
</div>
<div class="modal-body">
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Usuario.Login, new { #class = "col-lg-4 control-label" })
<div class="col-lg-7">
#Html.TextBoxFor(model => model.Usuario.Login, new { #class = "form-control"})
#Html.ValidationMessageFor(model => model.Usuario.Login)
</div>
</div>
Alright, the important part is the TextBoxFor, it renders me the next HTML:
<input class="form-control valid" data-val="true" data-val-remote="'Nombre de Usuario' is invalid." data-val-remote-additionalfields="*.Login" data-val-remote-url="/Validation/NoExisteUsuario" data-val-required="El campo Nombre de Usuario es obligatorio." id="Usuario_Login" name="Usuario.Login" type="text" value="">
As you see, the textbox name is: name="Usuario.Login"
And my controller action wich gets called by the Remote validation looks like this:
public JsonResult NoExisteUsuario([Bind(Prefix="Usuario")]string Login)
{
Usuario usuario = db.Usuarios.Find(Login);
if (usuario != null)
{
var MensajeDeError = string.Format("El usuario {0} ya existe", Login);
return Json(MensajeDeError, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
I set a breakpoint in this Action and it gets hit, but Login comes in null.
I checked with google chrome's debugger the http request header and it shows the form is getting submitted like this: Usuario.Login: asdasdasd.
The question is simple, how can i make it bind?
By the way, i'm using MVC5.
Thanks.
Well, i finally got it working, it seems i was setting the Prefix binding attribute wrongly.
Now my action looks like this:
public JsonResult NoExisteUsuario([Bind(Prefix="Usuario.Login")]string login)
{
Usuario usuario = db.Usuarios.Find(login);
if (usuario != null)
{
var MensajeDeError = string.Format("El usuario {0} ya existe", login);
return Json(MensajeDeError, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}