Search code examples
c#asp.net-mvcrazorasp.net-mvc-5html-helper

MVC Pass value from view to dynamic partial view


I'm trying to make a partial view, which will add dynamically as much fields as I input. I input number of fields, then I want to choose days of week in formed fields and do some work with this data in controller, but I have a problem with passing amount of days in partial view. Controller :

public class CoursesController : Controller
{
    private SchoolContext db = new SchoolContext();
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include = "CourseId,Name,Language,LanguageProficiency,StartDate,EndDate,TeacherId,NumberOfLessonsPerWeek")] Course course)
    {
        if (ModelState.IsValid)
        {
            db.Courses.Add(course);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(course);
    }
    public ActionResult ShowDaysOfweek(int? countDays)
    {
        //countDays = 2;
        ViewBag.CountDays = countDays;
        var days =  new List<DayOfWeek> { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday, DayOfWeek.Sunday };
        ViewBag.DaysOfWeek = new SelectList(days);
        return PartialView("ShowDaysOfweek");
    }
}

In this View I can add patial view by clicking button in script:

@model SchoolManagementSystem.Models.Course
@using (Ajax.BeginForm(new AjaxOptions { }))
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
    @Html.ValidationSummary(true, "", new { @class = "text-danger" }
    <div class="form-group">
        @Html.Label("Number Of Lessons Per Week", htmlAttributes: new { @class = "control-label col-md-3" })
        <div class="col-md-5">
            @Html.TextBox("NumberOfLessonsPerWeek", null, htmlAttributes: new { @class = "form-control", @type = "number", @id = "numberOfLessonsPerWeek" })
        </div>
        <div>
            <input type="button" value="Add days" id="Show" class="btn btn-default" />
        </div>
    </div>
    <div id="ShowResults">

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}
<script type="text/javascript">
    var url = '@Url.Action("ShowDaysOfweek", "Courses")';
    $('#Show').on("click", function () {
        var countDays = $('#numberOfLessonsPerWeek').val();
        url += '/?countDays=' + countDays;
         $('#ShowResults').load(url);
    })
</script>

Partial view:

@for (var i = 0; i < ViewBag.CountDays; i++)
{
<div class="form-group">
    @Html.Label("Day of week", htmlAttributes: new { @class = "control-label col-md-3" })
    <div class="col-md-5">
        @Html.DropDownList("DaysOfWeek", (IEnumerable<SelectListItem>)ViewBag.DaysOfWeek, htmlAttributes: new { @class = "form-control", style = "height: 35px" })
    </div>
</div>
}

Is it possible to do something? Thanks!


Solution

  • First create the hidden field with partial view url

    <input type="hidden" value="@Url.Action("ShowDaysOfweek", "Courses", new { countDays= "numberOfLessonsPerWeek" })" id="hdnURLShowDaysOfweek" />
    

    in javascript read the url and replace the parameter

    <script type="text/javascript">
        var url = $('#hdnURLShowDaysOfweek').val();
        $('#Show').on("click", function () {
        url = url.replace("numberOfLessonsPerWeek",$('#numberOfLessonsPerWeek').val());
                 $('#ShowResults').load(url);
        })
    </script>