Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remote Validation in ASP.Net MVC 3: How to use AdditionalFields in Action Method

I've been using the new ASP.Net MVC 3 RemoteAttribute to send a remote call to an action method that had a single parameter. Now I want to pass in a second parameter using the AdditionalFields property:

[Remote("IsEmailAvailable", "Users", AdditionalFields = "InitialEmail")] 

Where IntialEmail is a hidden field in the view. The action looks like so:

public JsonResult IsEmailAvailable(             string email,             string InitialEmail) { //etc. } 

When the view is rendered, the hidden field is populated, but when the Action method is triggered remotely, the value is an empty string.

I've seen elsewhere case sensitivity may be an issue, so I've ensured the Action method has the same case for both parameters.

Any other suggestions? This AdditionalFields used to be called Fields.

Thanks,

Beaudetious

like image 853
beaudetious Avatar asked Jan 20 '11 21:01

beaudetious


People also ask

Can one action method have multiple views?

Yes, completely possible. And, it can be multiple views, or even a FileResult or other result type.

What is the use of action method in MVC?

ASP.NET MVC Action Methods are responsible to execute requests and generate responses to it. By default, it generates a response in the form of ActionResult. Actions typically have a one-to-one mapping with user interactions.

How many types of action methods are there in MVC?

Figure 2: Types of Action Result There are two methods in Action Result. One is ActionResult() and another one is ExecuteResult().


1 Answers

Strange. It works for me:

Model:

public class MyViewModel {     [Required]     [Remote("IsEmailAvailable", "Home", AdditionalFields = "InitialEmail")]     public string Email { get; set; } } 

Controller:

public class HomeController : Controller {     public ActionResult Index()     {         return View(new MyViewModel());     }      [HttpPost]     public ActionResult Index(MyViewModel model)     {         return View(model);     }      public ActionResult IsEmailAvailable(string email, string initialEmail)     {         return Json(false, JsonRequestBehavior.AllowGet);     } } 

View:

@model AppName.Models.MyViewModel @{     ViewBag.Title = "Home Page"; } <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script> @using (Html.BeginForm()) {     @Html.TextBoxFor(x => x.Email)     @Html.ValidationMessageFor(x => x.Email)     <input type="hidden" name="InitialEmail" value="[email protected]" />     <input type="submit" value="OK" /> } 

IIRC there was some bug in ASP.NET MVC 3 RC2 with this remote validation that was fixed in the RTM.

like image 167
Darin Dimitrov Avatar answered Sep 28 '22 08:09

Darin Dimitrov