locked
Model IsValid RRS feed

  • Question

  • User1979860870 posted

    Hi

      How the below 2 lines works in the below code

    1.    return Json(new { success = true });
    2.   return Json(phone, JsonRequestBehavior.AllowGet);

    [HttpPost]
    public JsonResult Create(Phone phone)
    {
        if (ModelState.IsValid)
        {
            db.Phones.Add(phone);
            db.SaveChanges();
            return Json(new { success = true });
        }
        return Json(phone, JsonRequestBehavior.AllowGet);
    }

    Thanks

    Saturday, May 29, 2021 8:44 AM

Answers

  • User475983607 posted

    jagjit saini

    Hi

      How the below 2 lines works in the below code

    1.    return Json(new { success = true });
    2.   return Json(phone, JsonRequestBehavior.AllowGet);

    [HttpPost]
    public JsonResult Create(Phone phone)
    {
        if (ModelState.IsValid)
        {
            db.Phones.Add(phone);
            db.SaveChanges();
            return Json(new { success = true });
        }
        return Json(phone, JsonRequestBehavior.AllowGet);
    }

    Thanks

    Pretty simple.  The unknown "Phone" type in JSON format is return when the model is invalid.  Otherwise, phone is added to the DbContext, saved and { success = true } is returned.

    There is nothing stopping you from running this code your the Visual studio debugger.  The AllowGet is unnecessary since the Action is defined as a POST.  Plus the logic should check if phone exists before adding a new record.

    • Marked as answer by An0nym0u5User Tuesday, September 21, 2021 12:00 AM
    Saturday, May 29, 2021 11:08 AM

All replies

  • User475983607 posted

    jagjit saini

    Hi

      How the below 2 lines works in the below code

    1.    return Json(new { success = true });
    2.   return Json(phone, JsonRequestBehavior.AllowGet);

    [HttpPost]
    public JsonResult Create(Phone phone)
    {
        if (ModelState.IsValid)
        {
            db.Phones.Add(phone);
            db.SaveChanges();
            return Json(new { success = true });
        }
        return Json(phone, JsonRequestBehavior.AllowGet);
    }

    Thanks

    Pretty simple.  The unknown "Phone" type in JSON format is return when the model is invalid.  Otherwise, phone is added to the DbContext, saved and { success = true } is returned.

    There is nothing stopping you from running this code your the Visual studio debugger.  The AllowGet is unnecessary since the Action is defined as a POST.  Plus the logic should check if phone exists before adding a new record.

    • Marked as answer by An0nym0u5User Tuesday, September 21, 2021 12:00 AM
    Saturday, May 29, 2021 11:08 AM
  • User-1545767719 posted

      return Json(phone, JsonRequestBehavior.AllowGet);

    why don't you use:

    return View(phone);

    ?

    Saturday, May 29, 2021 10:55 PM