0

I have a problem for showing Level and Statues of course in course View enter image description here.

Here is my problem and the database does have data, but in add course service, it returns null in post method.

This is my AddCourse method:

public int AddCourse(Course course, IFormFile imgCourse, IFormFile courseDemo)
{
    course.CreateDate = DateTime.Now;
    course.CourseImageName = "no-photo.jpg";
    
    // TODO Check Image
    if (imgCourse != null && imgCourse.IsImage())
    {
        course.CourseImageName = NameGenerator.GenerateUniqCode() + Path.GetExtension(imgCourse.FileName);
        string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Course/Image", course.CourseImageName);

        using (var stream = new FileStream(imagePath, FileMode.Create))
        {
            imgCourse.CopyTo(stream);
        }

        ImageConvertor imgResizer = new ImageConvertor();
        string thumbPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Course/Thumb", course.CourseImageName);

        imgResizer.Image_resize(imagePath, thumbPath, 150);
    }

    if (courseDemo != null)
    {
        course.DemoFileName = NameGenerator.GenerateUniqCode() + Path.GetExtension(courseDemo.FileName);
        string demoPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Course/Demoes", course.DemoFileName);

        using (var stream = new FileStream(demoPath, FileMode.Create))
        {
            courseDemo.CopyTo(stream);
        }
    }

    _context.Add(course);
    _context.SaveChanges();

    return course.CourseId;
}

My Create Course Razor Page for Adding Course to Data Base Code:

@page
@model TopLearn.Web.Pages.Admin.Courses.CreateCourseModel
@{
    ViewData["Title"] = "افزودن دوره جدید";
}

<div class="row">
    <form method="post" enctype="multipart/form-data">
        <div class="col-md-8">
            <h2>اطلاعات دوره</h2>
            <hr />
            <div class="form-group">
                <label>عنوان دوره</label>
                <input type="text" asp-for="Course.CourseTitle" class="form-control">
                <span asp-validation-for="Course.CourseTitle"></span>
            </div>
            <div class="form-group">
                <label>گروه اصلی</label>
                <select class="form-control" asp-for="Course.GroupId" asp-items="@(ViewData["Groups"] as SelectList)"></select>
                <span asp-validation-for="Course.GroupId"></span>
            </div>
            <div class="form-group">
                <label>گروه فرعی</label>
                <select class="form-control" asp-for="Course.SubGroup" asp-items="@(ViewData["SubGroups"] as SelectList)"></select>
                <span asp-validation-for="Course.SubGroup"></span>
            </div>
            <div class="form-group">
                <label>مدرس دوره</label>
                <select class="form-control" asp-for="Course.TeacherId" asp-items="@(ViewData["Teachers"] as SelectList)"></select>
                <span asp-validation-for="Course.TeacherId"></span>
            </div>
            <div class="form-group">
                <label>شرح دوره</label>
                <textarea class="form-control" asp-for="Course.CourseDescription" rows="10"></textarea>
                <span asp-validation-for="Course.CourseDescription"></span>
            </div>
            <div class="form-group">
                <label>قیمت دوره</label>
                <input type="number" asp-for="Course.CoursePrice" value="0" class="form-control" />
                <span asp-validation-for="Course.CourseDescription"></span>
            </div>
            <div class="form-group">
                <label>فایل دمو دوره</label>
                <input type="file" name="demoUp">
                <span asp-validation-for="Course.CourseTitle"></span>
            </div>
            <div class="form-group">
                <label>کلمات کلیدی دوره</label>
                <input type="text" asp-for="Course.Tags" class="form-control">
                <p class="help-block">کلمات را با - جدا کنید</p>
                <span asp-validation-for="Course.CourseTitle"></span>
            </div>
            <input type="submit" value="ذخیره اطلاعات" class="btn btn-success" />
        </div>
        <div class="col-md-4">
            <p></p>
            <img id="imgCourse" class="thumbnail" src="/UserAvatar/Defult.jpg" />
            <div class="form-group">

                <label>انتخاب تصویر</label>
                <input type="file" name="imgCourseUp" id="imgCourseUp">
            </div>
            <div class="form-group">
                <label>سطح دوره</label>
                <select class="form-control" asp-for="Course.LevelId" asp-items="@(ViewData["Levels"] as SelectList)"></select>
                <span asp-validation-for="Course.LevelId"></span>
            </div>
            <div class="form-group">
                <label>وضعیت دوره</label>
                <select class="form-control" asp-for="Course.StatusId" asp-items="@(ViewData["Statues"] as SelectList)"></select>
                <span asp-validation-for="Course.StatusId"></span>
            </div>
        </div>
    </form>
</div>

@section Scripts
    {
    <script>
        $("#Course_GroupId").change(function () {
            $("#Course_SubGroup").empty();
            $.getJSON("/home/GetSubGroups/" + $("#Course_GroupId :selected").val(),
                function (data) {

                    $.each(data,
                        function () {
                            $("#Course_SubGroup").append('<option value=' + this.value + '>' + this.text + '</option>');

                        });

                });


        });

        function readURL(input) {

            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    $('#imgCourse').attr('src', e.target.result);
                }

                reader.readAsDataURL(input.files[0]);
            }
        }

        $("#imgCourseUp").change(function () {
            readURL(this);
        });
    </script>

    <script src="https://cdn.ckeditor.com/4.9.2/standard/ckeditor.js"></script>
    <script>

        CKEDITOR.replace('Course_CourseDescription', {
            customConfig: '/js/Config.js'
        });

    </script>
}

Create Course Razor Page Backend Code:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using TopLearn.Core.Services.InterFaces;
using TopLearn.DataLayer.Entities.Course;

namespace TopLearn.Web.Pages.Admin.Courses
{
    public class CreateCourseModel : PageModel
    {
        private ICourceService _courseService;

        public CreateCourseModel(ICourceService courseService)
        {
            _courseService = courseService;
        }

        [BindProperty]
        public Course Course { get; set; }

        public void OnGet()
        {
            var groups = _courseService.GetGroupForManageCourse();
            ViewData["Groups"] = new SelectList(groups, "Value", "Text");

            var subGrous = _courseService.GetSubGroupForManageCourse(int.Parse(groups.First().Value));
            ViewData["SubGroups"] = new SelectList(subGrous, "Value", "Text");

            var teachers = _courseService.GetTeachers();
            ViewData["Teachers"] = new SelectList(teachers, "Value", "Text");

            var levels = _courseService.GetLevels();
            ViewData["Levels"] = new SelectList(levels, "Value", "Text");

            var statues = _courseService.GetStatus();
            ViewData["Statues"] = new SelectList(statues, "Value", "Text");
        }

        public IActionResult OnPost(IFormFile imgCourseUp, IFormFile demoUp)
        {
            if (!ModelState.IsValid)
                return Page();

            _courseService.AddCourse(Course, imgCourseUp, demoUp);

            return RedirectToPage("Index");
        }
    }
}

This my view:

@using TopLearn.Core.Convertors
@model TopLearn.DataLayer.Entities.Course.Course
@{
    ViewData["Title"] = Model.CourseTitle;
}

<div class="container">
    <nav aria-label="breadcrumb">
        <ul class="breadcrumb">
            <li class="breadcrumb-item"><a href="#"> تاپ لرن </a></li>
            <li class="breadcrumb-item active"><a href="#"> دوره ها </a></li>
            <li class="breadcrumb-item active" aria-current="page"> @Model.CourseTitle </li>
        </ul>
    </nav>
</div>

<div class="container">
    <section class="term-content">
        <header><h1> @Model.CourseTitle </h1></header>
        <div class="row">

            <div class="col-md-8 col-sm-12 col-xs-12 pull-left">
                <section class="term-description">
                    <img src="/course/image/@Model.CourseImageName">

                    @Html.Raw(Model.CourseDescription)

                    <h2> سرفصل های این دوره : </h2>
                    <ul>
                        @foreach (var item in Model.CourseEpisodes)
                        {
                            <li> <h3> @item.EpisodeTitle </h3>  
                            @if (item.IsFree)
                            {
                                 <i> رایگان </i>
                            }
                            else
                            {
                                <i> نقدی </i> 
                            }
                            <span>@item.EpisodeTime</span></li>
                
                        }
                    </ul>
                </section>

                <section class="user-comments">
                    <header><h3> نظرات کاربران </h3></header>
                    <div class="inner">
                        <form>
                            <div class="row">
                                <div class="col-md-4 col-sm-12 col-xs-12">
                                    <div class="form-group">
                                        <input type="text" class="form-control" placeholder="نام و نام خانوادگی">
                                    </div>
                                    <div class="form-group">
                                        <input type="text" class="form-control" placeholder="ایمیل">
                                    </div>
                                    <div class="form-group">
                                        <input type="text" class="form-control" placeholder="شماره تماس">
                                    </div>
                                </div>
                                <div class="col-md-8 col-sm-12 col-xs-12">
                                    <div class="form-group">
                                        <textarea class="form-control" placeholder="متن نظر"></textarea>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-8 col-sm-7 col-xs-7">
                                            <div class="form-group">
                                                <input type="text" class="form-control" placeholder="کد امنیتی">
                                            </div>
                                        </div>
                                        <div class="col-md-4 col-sm-5 col-xs-5">
                                            <img src="images/captcha.jpg">
                                        </div>
                                    </div>
                                </div>
                                <div class="col-xs-12">
                                    <button type="submit" class="btn btn-success"> ثبت دیدگاه </button>
                                </div>
                            </div>
                        </form>

                        <div class="comment-list">
                            <!-- row -->
                            <div class="comment-row">
                                <img src="images/pic/avatar.jpg">
                                <div class="left-col">
                                    <h3> میترا رحیمی </h3>
                                    <span>12/03/1397</span>
                                    <p>
                                        لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ و با استفاده از طراحان گرافیک است. چاپگرها و متون بلکه روزنامه و مجله در ستون و سطرآنچنان که لازم است
                                    </p>
                                </div>
                            </div>
                            <!-- /row -->
                            <!-- row -->
                            <div class="comment-row">
                                <img src="images/pic/avatar.jpg">
                                <div class="left-col">
                                    <h3> میترا رحیمی </h3>
                                    <span>12/03/1397</span>
                                    <p>
                                        لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ و با استفاده از طراحان گرافیک است. چاپگرها و متون بلکه روزنامه و مجله در ستون و سطرآنچنان که لازم است
                                    </p>
                                </div>
                            </div>
                            <!-- /row -->
                            <!-- row -->
                            <div class="comment-row">
                                <img src="images/pic/avatar.jpg">
                                <div class="left-col">
                                    <h3> میترا رحیمی </h3>
                                    <span>12/03/1397</span>
                                    <p>
                                        لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ و با استفاده از طراحان گرافیک است. چاپگرها و متون بلکه روزنامه و مجله در ستون و سطرآنچنان که لازم است
                                    </p>
                                </div>
                            </div>
                            <!-- /row -->
                            <!-- row -->
                            <div class="comment-row">
                                <img src="images/pic/avatar.jpg">
                                <div class="left-col">
                                    <h3> میترا رحیمی </h3>
                                    <span>12/03/1397</span>
                                    <p>
                                        لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ و با استفاده از طراحان گرافیک است. چاپگرها و متون بلکه روزنامه و مجله در ستون و سطرآنچنان که لازم است
                                    </p>
                                </div>
                            </div>
                            <!-- /row -->
                            <!-- row -->
                            <div class="comment-row">
                                <img src="images/pic/avatar.jpg">
                                <div class="left-col">
                                    <h3> میترا رحیمی </h3>
                                    <span>12/03/1397</span>
                                    <p>
                                        لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ و با استفاده از طراحان گرافیک است. چاپگرها و متون بلکه روزنامه و مجله در ستون و سطرآنچنان که لازم است
                                    </p>
                                </div>
                            </div>
                            <!-- /row -->

                            <nav aria-label="Page navigation">
                                <ul class="pagination justify-content-center">
                                    <li class="page-item">
                                        <a class="page-link" href="#" aria-label="Previous">
                                            <span aria-hidden="true"><i class="zmdi zmdi-chevron-right"></i></span>
                                        </a>
                                    </li>
                                    <li class="page-item"><a class="page-link" href="#">1</a></li>
                                    <li class="page-item"><a class="page-link" href="#">2</a></li>
                                    <li class="page-item"><a class="page-link" href="#">3</a></li>
                                    <li class="page-item">
                                        <a class="page-link" href="#" aria-label="Next">
                                            <span aria-hidden="true"><i class="zmdi zmdi-chevron-left"></i></span>
                                        </a>
                                    </li>
                                </ul>
                            </nav>

                        </div>
                    </div>
                </section>
            </div>

            <aside class="col-md-4 col-sm-12 col-xs-12 pull-right">
                <div class="statistics">
                    <ul>
                        <li>
                            <span> مدت دوره </span>

                            @{
                                TimeSpan time = new TimeSpan(Model.CourseEpisodes.Sum(e => e.EpisodeTime.Ticks));
                            }
                            <i> @time </i>
                        </li>
                        <li>
                            <span> تعداد ویدیوها </span>
                            <i> @Model.CourseEpisodes.Count </i>
                        </li>
                        <li>
                            <span> تعداد دانشجوها </span>
                            <i> 0 نفر </i>
                        </li>
                    </ul>

                   @if (Model.CoursePrice != 0)
                   {
                       <a href=""> شرکت در دوره : @Model.CoursePrice.ToString("#,0") تومان </a>
                   }
                </div>

                <article class="teacher-info">
                    <img src="/UserAvatar/@Model.User.UserAvatar">
                    <h2> مدرس : @Model.User.UserName </h2>
                </article>

                <article class="term-info">
                    <h2> اطلاعات این دوره </h2>
                    <ul>
                       
                        <li>سطح دوره: @Model.CourseStatus.StatusTitle</li>
                        <li>وضعیت دوره: @Model.CourseLevel.LevelTitle</li>
                        @if (Model.CoursePrice != 0)
                        {
                            <li>قیمت : @Model.CoursePrice.ToString("#,0") تومان</li>
                        }
                        else
                        {
                            <li> رایگان </li>
                        }
                        <li>تاریخ ثبت این دوره : @Model.CreateDate.ToShamsi()</li>
                        <li>آخرین بروزرسانی دوره : @Model.UpdateDate?.ToShamsi()</li>
                    </ul>
                </article>

                <div class="share-layer">
                    <span> به اشتراک گذاری </span>
                    <a href=""><i class="zmdi zmdi-facebook"></i></a>
                    <a href=""><i class="zmdi zmdi-google-old"></i></a>
                    <a href=""><i class="zmdi zmdi-twitter"></i></a>
                    <a href=""><i class="zmdi zmdi-linkedin"></i></a>
                </div>

                @if (Model.Tags != null)
                {
                    <div class="tags-layer">
                        @foreach (string tag in Model.Tags.Split('-',StringSplitOptions.RemoveEmptyEntries))
                        {
                        <a href="/Course?filter=@tag"> @tag </a>
                        }
                    </div>
                }

            </aside>
        </div>
    </section>
</div>

And here is my backend code:

using Microsoft.AspNetCore.Mvc;
using TopLearn.Core.Services.InterFaces;

namespace TopLearn.Web.Controllers
{
    public class CourseController : Controller
    {
        ICourceService _courseServise;

        public CourseController(ICourceService courseServise)
        {
            _courseServise = courseServise;
        }

        public IActionResult Index(int pageId = 1, string filter = ""
            , string getType = "all", string orderByType = "date",
            int startPrice = 0, int endPrice = 0, List<int> selectedGroups = null)
        {
            ViewBag.selectedGroups = selectedGroups;
            ViewBag.Groups = _courseServise.GetAllGroup();
            ViewBag.pageId = pageId;

            return View(_courseServise.GetCourse(pageId, filter, getType, orderByType, startPrice, endPrice, selectedGroups, 9));
        }

        [Route("ShowCourse/{id}")]
        public IActionResult ShowCourse(int id)
        {
            var course = _courseServise.GetCourseForShow(id);

            if (course == null)
            {
                return NotFound();
            }

            return View(course);
        }
    }
}

I'm just tracing but I don't understand problem

2
  • are you sure that's the right view code? I don't see anything that looks like form data for adding a course - only for adding a comment. Commented Oct 17, 2023 at 20:33
  • This is my showcourse view not addcourse and my problem is statues title and levele title return null reference Commented Oct 18, 2023 at 4:53

1 Answer 1

0

According to your codes, I found you just show the statues title and levele title not add them to the request body when the post method.

Normally, for this, we could put it inside a input hidden and asp.net core will add the input hidden value to the backend during posting.

More details, you could refer to below example:

Since I don't have your model, I create a simple one.

public class Course
{
    public CourseLevel CourseLevel { get; set; }
}

public class CourseLevel
{
    public string StatusTitle { get; set; }

    public string LevelTitle { get; set; }
}

Controller:

    public IActionResult Index()
    {


        var test = new Course() {  CourseLevel = new CourseLevel { LevelTitle="1", StatusTitle="1" } };

        return View(test);
    }

View:

<form asp-action="AddCourse" asp-controller="Home">

    <ul>
        <li>سطح دوره: @Model.CourseLevel.StatusTitle</li>
        <li>وضعیت دوره: @Model.CourseLevel.LevelTitle</li>
    </ul>
    <input type="hidden"  asp-for="CourseLevel.StatusTitle"/>
    <input type="hidden" asp-for="CourseLevel.LevelTitle" />
    <input type="submit" value="test" />
</form>

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

6 Comments

This Code of my view for showing course not for adding course to database
for Adding course I'm use razor page but this view code for showing course with level title and statues title
You just need to understand how it works and modify your codes, you could check the request body to see if it contains the title firstly. If it doesn't contain it, you should add input hidden or else to let the form post it.
I added a new course in the database, but I still have this problem but today I'll check Codes
Thank for Helping My problem has been solved Course Model Need Foreign Key for Relation between Course And status and level Models
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.