Home > Enterprise >  How can I return Id when model state cannot be work?
How can I return Id when model state cannot be work?

Time:08-29

I am in "User Add" page. I have an Id which coming from "Visa Type" page.

enter image description here

When my page cannot be pair with model state, the Id doesn't exist in the URL. I need this Id. How can I return again?

enter image description here

Controller

    [HttpGet]
    public IActionResult AddUser(int visaTypeId)
    {
        ViewBag.Id = visaTypeId;

        Guid g = Guid.NewGuid();
        ViewBag.UniqueUser = g;
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> AddUser(UserModel userModel, string uniqueUser, int visaTypeId)
    {
        if (ModelState.IsValid)
        {
            var result = await _client.PostAsJsonAsync<UserModel>("users/adduser", userModel);
            var response = await result.Content.ReadAsStringAsync();
            var responseModel = JsonConvert.DeserializeObject<ResponseModel>(response);
            if (responseModel.Success == false)
            {
                //ViewBag.Message = responseModel.Message;
                ModelState.AddModelError("", responseModel.Message);
            }

            if (result.IsSuccessStatusCode)
            {
                return RedirectToAction("AddApplicant", "Applicant", new { uniqueUser = uniqueUser });
            }
        }

        return View();
    }

CodePudding user response:

You can pass back whatever you obtain from your view.

[HttpPost]
        public async Task<IActionResult> AddUser(UserModel userModel, string uniqueUser, int visaTypeId)
        {
            if (ModelState.IsValid) 
            {
                var result = await _client.PostAsJsonAsync<UserModel>("users/adduser", userModel);
                var response = await result.Content.ReadAsStringAsync();
                var responseModel = JsonConvert.DeserializeObject<ResponseModel>(response);
                if (responseModel.Success == false)
                {
                    //ViewBag.Message = responseModel.Message;
                    ModelState.AddModelError("", responseModel.Message);
                }
    
                if (result.IsSuccessStatusCode)
                {
                    return RedirectToAction("AddApplicant", "Applicant", new { uniqueUser = uniqueUser });
                }
            }
           ViewBag.VisaTypeId = VisaTypeId;
           ViewBag.uniqueUser = uniqueUser;
            return View(userModel);
        }
  • Related