0

I am updating database values using an action method but I am using ajax call to send updated values into that method so I am not binding model with this method so how can I validate the model for this action method such as I am not binding this with my method?

public ActionResult Update(int id, double? value)
    {
        if (!ModelState.IsValid)
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json("Not valid model");
        }

        if (ModelState.IsValid) { 
         var oldTag = db.Tags.Where(x => x.Id == id).FirstOrDefault();
         List<UpdatedData> updatedDatas = new List<UpdatedData> {
         new UpdatedData
         {
             Id=id,
             OldTagValue=oldTag.TagValue,
             NewTagValue=value,
             TagName = oldTag.TagName
         }
        };
            obj.updatedDatas = new List<UpdatedData>();
            obj.updatedDatas.AddRange(updatedDatas);
            return PartialView("_Update_Confirmation", obj);
        }
        return View("Index");

    }

1 Answers1

0

you can change Update method

public class ProfileViewModel
{
    [Required]
    public int Id { get; set; }

    public double? value { get; set; }
}

then

public ActionResult Update(ProfileViewModel viewModel)
{
    if (!ModelState.IsValid)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json("Not valid model");
    }
 //...
}

The sample DataAnnotations model binder will fill model state with validation errors taken from the DataAnnotations attributes on your model.

Reza Jenabi
  • 3,884
  • 1
  • 29
  • 34
  • I am not passing the model as a parameter to the method instead of that I am passing two values using ajax call. –  Jan 01 '20 at 07:52