Reputation: 5670
My code is like this
public class Payer
{
public int PayerId { get; set; }
[Remote("PayerNameExists", "Payer", "Payer name already exists.", AdditionalFields = "PayerID"), Required]
public string Name { get; set; }
public double PatientContribution { get; set; }
}
Inside controller
public JsonResult PayerNameExists(string Name,int PayerID=0)
{
var user = db.Payer.Where(x => x.Name == Name.Trim()&&x.PayerId!=PayerID);
return !user.Any() ?
Json(true, JsonRequestBehavior.AllowGet) :
Json(string.Format("{0} is already exists.", Name),
JsonRequestBehavior.AllowGet);
}
and in view (Edit
)
@Html.TextBoxFor(model => model.Name)
My problem is that inside the function PayerNameExists
PayerID
always comes as zero
I expect to get my model ID out there. Can anyone tell me how I can achieve this?
Note: Data send from client side is liek this
/Payer/PayerNameExists?area=Payer%20name%20%20already%20exists.&Name=ICICIx&PayerID=undefined
Upvotes: 2
Views: 949
Reputation: 33326
Your problem is a miss-match in PayerID
and PayerId
this:
AdditionalFields = "PayerID"
It needs to be this:
AdditionalFields = "PayerId"
And you method needs to be this:
public JsonResult PayerNameExists(string Name,int PayerId=0)
Or change you model to:
public int PayerID { get; set; }
Update
I needed to change the model to PayerID
as mentioned above to get this working, not all agree as it was downvoted.
However I also needed to do the following:
Supply an Html.Helper
to post the PayerID
back i.e. @Html.HiddenFor(model => model.PayerID)
, otherwise it was going to the default.
If you are having an un-specified error you may want to check the rendered html, it will need to have something like the following:
<input data-val="true" data-val-remote="'Name' is invalid." data-val-remote-additionalfields="*.Name,*.PayerID" data-val-remote-url="/Home/PayerNameExists" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="Name" class="input-validation-error">
Note data-val-remote-additionalfields
as this is what jquery needs to render to find the additional properties, if it is different or missing the setting up has failed so check you have references for jquery.validate.js
and jquery.validate.unobtrusive.js"
also jquery.
The attribute would not work for me, I had to remove the error message. This comes back from the server anyway.
[Remote("PayerNameExists", "Home", AdditionalFields = "PayerID"), Required]
Also from you rendered link in the update i.e.
/Payer/PayerNameExists?area=Payer%20name%20%20already%20exists.&Name=ICICIx&PayerID=undefined
It is picking up your intended error message as an area route value, so remove it as I mentioned above.
Screen shots
Upvotes: 2