Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remote validation doesn't pass data to action

I have model:

public class MyModel
...fields
[Remote(ActionName, ControllerName)]
public string SomeNumber { get; set; }
..fields

And have a action in ControllerName controller:

public JsonResult ActionName(string someNumber)
{...}

But when actions is invoked the parameter someNumber is allways null. And when I try to debug it I get

GET /ControllerName/ActionName?MyModel.SomeNumber =34189736 

How can I make it work? (I can't pass whole model MyModel, and cant change MyModel.SomeNumber name of field in my view)

UPD. Input in my view:

<input data-val="true" data-val-remote-additionalfields="*.SomeNumber" data-val-remote-url="/ControllerName/ActionName" id="MyModel_SomeNumber" name="MyModel.SomeNumber" type="text" value="34189734" class="valid">

UPD solved! :) I create new model with single field SomeNumber and use prefix:

SomeNumber([Bind(Prefix = "MyModel")]MySingleFieldModel model)
like image 434
Roman Bats Avatar asked Feb 17 '23 13:02

Roman Bats


1 Answers

If you're using nested ViewModels, you'll need to accept the parent ViewModel as the argument in your Validation action. For example:

public class ParentViewModel
{
    public UserViewModel User {get; set; }

    //....
}

public class UserViewModel 
{
    [Remote("UniqueUsername", "Validation")]
    public string Username { get; set; }

    //....
}

In ValidationController:

public class ValidationController : Controller
{ 
     public JsonResult UniqueUsername(ParentViewModel Registration) 
     {
        var Username = Registration.User.Username; //access the child view model property like so

        //Validate and return JsonResult

     }
}
like image 191
Pandagrrl Avatar answered Feb 26 '23 18:02

Pandagrrl