Search code examples
c#asp.net-mvcasp.net-mvc-4asp.net-mvc-5

Model gets NULL while passing as parameter from POST method to GET method of same controller in ASP.NET MVC using C#


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.


Solution

  • 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");
        }
    }