skip to Main Content

I’m new to Asp .net core, I was trying to build form using CRUD opertaions.Since i’m trying to save the new data it redirecting to form action instead of homepage where my list is visible. I want my data to show on studentlist since im redirecting it to StudentList but this isnt happening. Look on the internet but couldn’t find any relevant answer to it.
Form Page
After Saving the data

```Controller
using Microsoft.AspNetCore.Mvc;
using WebAppDotNetCoreCrudNew.Models;

namespace WebAppDotNetCoreCrudNew.Controllers
{
    public class StudentController : Controller
    {
        private readonly StudentContext _Db;
        public StudentController(StudentContext Db)
        {
            _Db = Db;
        }
        public IActionResult StudentList()
        {
            try
            {
                var stdList = from a in _Db.tbl_Student
                              join b in _Db.tbl_Department
                              on a.DepID equals
                              b.ID into Dep
                              from b in Dep.DefaultIfEmpty()

                              select new Student
                              {
                                  ID = a.ID,
                                  Name = a.Name,
                                  Fname=a.Fname,
                                  Mobile=a.Mobile,
                                  Email=a.Email,
                                  Description=a.Description,
                                  DepID=a.DepID,

                                  Department=b==null?"":b.Department
                              };

                return View(stdList);
            }
            catch (Exception ex)
            {
                return View();
            }
            
        }

        public IActionResult Create()
        {
            loadDDL();
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> AddStudent(Student obj)
        {
            try
            {
                
                if(ModelState.IsValid)
                {
                    
                    if (obj.ID == 0)
                    {
                        _Db.tbl_Student.Add(obj);
                        await _Db.SaveChangesAsync();
                    }
                    
                    return RedirectToAction("StudentList");

                }
                return View();
            }
            catch (Exception ex )
            {
                return RedirectToAction("StudentList");
            }
        }


        private void loadDDL()
        {
            try
            {
                List<Departments> depList = new List<Departments>();
                depList = _Db.tbl_Department.ToList();
                depList.Insert(0, new Departments { ID = 0, Department = "Please Select" });

                ViewBag.DepList = depList;
            }
            catch (Exception ex)
            {

            }
        }
    }
}
@model WebAppDotNetCoreCrudNew.Models.Student

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>


<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="AddStudent">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            
            <div class="form-group">
                <input type="hidden" asp-for="ID" />
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Fname" class="control-label"></label>
                <input asp-for="Fname" class="form-control" />
                <span asp-validation-for="Fname" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Email" class="control-label"></label>
                <input asp-for="Email" class="form-control" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            
            <div class="form-group">
                <label asp-for="Mobile" class="control-label"></label>
                <input asp-for="Mobile" class="form-control" />
                <span asp-validation-for="Mobile" class="text-danger"></span>
            </div>

            <div class="form-group">
                 <label asp-for="Department" class="control-label"></label>
                 <select asp-for="DepID" class="form-control" asp-items="@(new SelectList(ViewBag.DepList,"ID","Department"))">

                 </select>
            </div>


            <div class="form-group">
                <label asp-for="Description" class="control-label"></label>
                <input asp-for="Description" class="form-control" />
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
                <a asp-action="StudentList" class="btn btn-outline-success">Student List</a>
            </div>
        </form>
    </div>
</div>



@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

2

Answers


  1. Just change the redirect to return View() under the Add Student action

    [HttpPost]
            public async Task<IActionResult> Create(Student obj) //change the name to create
            {
                try
                {
                    
                    if(ModelState.IsValid)
                    {
                        
                        if (obj.ID == 0)
                        {
                            _Db.tbl_Student.Add(obj);
                            await _Db.SaveChangesAsync();
                        }
                        
                        return View(obj); //If you want to display the data that you have save otherwise just put ---> return View();
    
                    }
                    return View();
                }
                catch (Exception ex )
                {
                    return View(obj);
                }
            }
    
    Login or Signup to reply.
  2. enter image description here

    Problem: 1:

    Have gone through your error. This is very obvious because the error clearly stated that it doesn’t find the AddStudent view as it’s not there.

    How To Resolve:

    As your student add view is named as create so your code should be as below:

            [HttpPost]
            public async Task<IActionResult> AddStudent(Student obj)
            {
                try
                {
    
                    if (ModelState.IsValid)
                    {
    
                        if (obj.ID == 0)
                        {
                            _context.Students.Add(obj);
                            await _context.SaveChangesAsync();
                        }
    
                        return RedirectToAction("StudentList");
    
                    }
                    return RedirectToAction("Create");
                }
                catch (Exception ex)
                {
                    return RedirectToAction("StudentList");
                }
            }
    

    Note: You cannot write return View() as your student add view created as Create so after adding new student if you return just View() it will eventually encounter that error which you are currently encountering.

    Problem: 2:

    Another problem is your ModelState.IsValid in AddStudent(Student obj) will always be false as you have set <input type="hidden" asp-for="ID" /> in your view which doesn’t make any sense. Because in AddStudent page (that is Create in your scenario) ID will always be 0 there’s no point of set this as hidden which is set ModelState.IsValid value as false. So your code should be as below:

    Create View:

    @model WebAppDotNetCoreCrudNew.Models.Student
    
    @{
        ViewData["Title"] = "Create";
    }
    
    <hr />
    <div class="row">
        <div class="col-md-4">
            <form asp-action="AddStudent">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                
                <div class="form-group">
                    <label asp-for="Name" class="control-label"></label>
                    <input asp-for="Name" class="form-control" />
                    <span asp-validation-for="Name" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Fname" class="control-label"></label>
                    <input asp-for="Fname" class="form-control" />
                    <span asp-validation-for="Fname" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Email" class="control-label"></label>
                    <input asp-for="Email" class="form-control" />
                    <span asp-validation-for="Email" class="text-danger"></span>
                </div>
                
                <div class="form-group">
                    <label asp-for="Mobile" class="control-label"></label>
                    <input asp-for="Mobile" class="form-control" />
                    <span asp-validation-for="Mobile" class="text-danger"></span>
                </div>
    
                <div class="form-group">
                     <label asp-for="Department" class="control-label"></label>
                     <select asp-for="DepID" class="form-control" asp-items="@(new SelectList(ViewBag.DepList,"ID","Department"))">
    
                     </select>
                </div>
    
    
                <div class="form-group">
                    <label asp-for="Description" class="control-label"></label>
                    <input asp-for="Description" class="form-control" />
                    <span asp-validation-for="Description" class="text-danger"></span>
                </div>
                
                <div class="form-group">
                    <input type="submit" value="Save" class="btn btn-primary" />
                    <a asp-action="StudentList" class="btn btn-outline-success">Student List</a>
                </div>
            </form>
        </div>
    </div>
    
    
    
    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }
    

    Controller:

            [HttpPost]
            public async Task<IActionResult> AddStudent(Student obj)
            {
                try
                {
    
                    if (ModelState.IsValid)
                    {
    
                        if (obj.ID == 0)
                        {
                            _context.Students.Add(obj);
                            await _context.SaveChangesAsync();
                        }
    
                        return RedirectToAction("StudentList");
    
                    }
                    return RedirectToAction("Create");
                }
                catch (Exception ex)
                {
                    return RedirectToAction("StudentList");
                }
            }
    

    Output:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search