Home > Net >  Model gets NULL while passing as parameter from POST method to GET method of same controller in ASP.
Model gets NULL while passing as parameter from POST method to GET method of same controller in ASP.

Time:09-17

I was not able to get model and its value in a GET method which is passed by POST of same controller. Please find the code snippet below. Please help me to resolve it.

Model:

public class country
{
    public string CountryCode { get; set; }
    public long? CountryId { get; set; }
}

Controller:

[HttpGet]
public async Task<ActionResult> Create()
{
    return View();
}

[HttpPost]
public async Task<ActionResult> Create(Country _country)
{
    var data = await checkduplicate(_country);

    if (!data.status)
    {
        ModelState.AddModelError("Name", data.ErrorMessage);
        return RedirectToAction("Edit", new {_country});
    }
    else
    {
        return RedirectToAction("Index");
    }
}

public async Task<ActionResult> Edit(Country _country)
{
    return View("Create", _country);
}

In this sample, I have given only two values but actual I have around 8 parameters. Please suggest it. I have used razor view page.

Thanks in advance.

CodePudding user response:

I got the answer, it was an minor error, while sending the model via post end. It should be as below. I have included the keyword "new" in it. On removing the keyword new, it is working fine.

[HttpPost]
public async Task<ActionResult> Create(Country _country)
{
    var data = await checkduplicate(_country);

    if (!data.status)
    {
        ModelState.AddModelError("Name", data.ErrorMessage);
        return RedirectToAction("Edit", _country);
    }
    else
    {
        return RedirectToAction("Index");
    }
}
  • Related