0

Hi I have this in my mvc 4 application. Once you add a festival to the system and I want to add an event to that festival by passing an id. Can anyone help me? here is my controller along with my view, viewmodel and model. I am getting an error :

The parameters dictionary contains a null entry for parameter 'festID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Create2(MyFestival.Models.EventsVM, Int32)' in 'MyFestival.Controllers.EventsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

    [HttpGet]
    public ActionResult Create2(int festID)
    {
        EventsVM events = new EventsVM { festivalID = festID };

        events.eType = db.EType.ToDictionary(p => p.ID, q => q.EType);
        events.eType.Add(-1, "----- Add New Event Type -----");

        events.eventsDate = DateTime.Now;
        events.startTime = DateTime.Now;
        events.endTime = DateTime.Now;

        return View(events);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create2(EventsVM model, int festID)
    {
        if (ModelState.IsValid != true)
        {
            if (model.selectedEType != -1)
            {
                //db.save stuff from create.
                Events Newevent = new Events();
                Newevent.EndTime = model.endTime;
                Newevent.StartTime = model.startTime;
                Newevent.EventsDate = model.eventsDate = DateTime.Now;
                Newevent.EventsName = model.EventsName;
                Newevent.EType = db.EType.Where(p => p.ID == model.selectedEType).Single();
                Newevent.Location = model.Location;
                if (Request.Files.Count != 0)
                {
                    string fileName = Guid.NewGuid().ToString();
                    string serverPath = Server.MapPath("~\\Content\\EventPicture");
                    Bitmap newImage = new Bitmap(Request.Files[0].InputStream);
                    newImage.Save(serverPath + "\\" + fileName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    model.eventsImage = "Content/EventPicture/" + fileName + ".jpg";

                    Newevent.FestivalID = model.festivalID = festID;

                    db.Events.Add(Newevent);
                    db.SaveChanges();
                    //Change the model.festivalID to Newevent.FestivalID
                    return RedirectToAction("Details", "Festival", new { id = Newevent.FestivalID });
                }
                else
                {
                    db.Events.Add(Newevent);
                    db.SaveChanges();
                    //Change the model.festivalID to Newevent.FestivalID
                    return RedirectToAction("Details", "Festival", new { id = Newevent.FestivalID });
                }
            }
            ModelState.AddModelError("", "No Event Type Picked");
        }

        model.eType = db.EType.ToDictionary(p => p.ID, q => q.EType);
        model.eType.Add(-1, "----- Add New Event Type -----");
        model.eventsDate = DateTime.Now;
        model.startTime = DateTime.Now;
        model.endTime = DateTime.Now;

        return View(model);
    }

Here is my Model

public class Events
{
    [Required]
    public int ID { get; set; }

    [Required]
    public int FestivalID { get; set; }

    [Required(ErrorMessage="Please input the Event Name.")]
    [Display(Name = "Event name"), StringLength(100)]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public string EventsName { get; set; }

    [Display(Name = "Event date")/*, DataType(DataType.Date)*/]
    [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
    [Required(ErrorMessage = "Please input the Event's Date.")]
    public DateTime EventsDate { get; set; }

    [Display(Name = "Start Time"), DataType(DataType.Time)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")]
    [Required(ErrorMessage = "Please input the Event's Start Time.")]
    public DateTime StartTime { get; set; }

    [Display(Name = "End Time"), DataType(DataType.Time)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")]
    [Required(ErrorMessage = "Please input the Event's end time.")]
    public DateTime EndTime { get; set; }

    [Required]
    [Display(Name = "Location")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public string Location { get; set; }

    [Required]
    [Display(Name = "Event Type")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public virtual EventType EType { get; set; }

    [Display(Name = "Event Logo")]
    [DataType(DataType.Upload)]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public string EventLogo { get; set; }
}

ViewModel

public class EventsVM
{
    [Required]
    [Display(Name = "Event Type")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public Dictionary<int, string> eType { get; set; }

    public int selectedEType { get; set; }

    [Required]
    public int ID { get; set; }

    [Required]
    public int festivalID { get; set; }

    [Required]
    [Display(Name = "Event Name"), StringLength(100)]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public string EventsName { get; set; }

    [Required]
    [Display(Name = "Event Date")/*, DataType(DataType.Date)*/]
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
    public DateTime eventsDate { get; set; }

    [Display(Name = "Start Time"), DataType(DataType.Time)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")]
    [Required(ErrorMessage = "Please input the Event's Start Time.")]
    public DateTime startTime { get; set; }

    [Display(Name = "End Time"), DataType(DataType.Time)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")]
    [Required(ErrorMessage = "Please input the Event's end time.")]
    public DateTime endTime { get; set; }

    [Required]
    [Display(Name = "Location")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public string Location { get; set; }

    public HttpPostedFileWrapper imageFile { get; set; }
    [Display(Name="Event Image")]
    public string eventsImage { get; set; }
}

And here is my View

@model MyFestival.Models.EventsVM

@{
  ViewBag.Title = "Create Event";
  Layout = "~/Views/Shared/Festival.cshtml";
}

<h2>Add an event for #@Model.festivalID</h2>

@using (Html.BeginForm())
{
@*@using (Html.BeginForm("Create2", "Events", FormMethod.Post, new {enctype="multipart/form-data"}))
{*@
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <hr />
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.LabelFor(model => model.EventsName, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                <input class="form-control" id="EventsName" required="required" style="width: 210px" name="EventsName" placeholder="Please enter event name" />
                @*@Html.EditorFor(model => model.EventsName, new { @class = "form-control", @style = "width:250px" })*@
            </div>
            @Html.ValidationMessageFor(model => model.EventsName, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.eventsDate, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
                @Html.TextBoxFor(model => model.eventsDate, new { @class = "form-control datepicker", @style = "width:210px" })
            </div>
            @Html.ValidationMessageFor(model => model.eventsDate, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.startTime, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
                <input id="startTime" name="startTime" required="required" class="form-control bootstrap-timepicker" style="width: 210px" />
                @*@Html.EditorFor(model => model.startTime, new { @class = "form-control", @style = "width:250px" })*@
            </div>
            @*@Html.EditorFor(model => model.startTime, new { @class = "form-control" })*@
            @Html.ValidationMessageFor(model => model.startTime, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.endTime, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class='input-group date' id='datetimepicker4'>
                <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
                <input name="endTime" id="endTime" type='text' class="form-control bootstrap-timepicker" style="width: 210px" />
                @*@Html.TextBoxFor(model => model.startDate, new { @class = "form-control datepicker", @style = "width:210px" })*@
            </div>
            @Html.ValidationMessageFor(model => model.endTime, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.eType, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-tag"></i></span>
                @Html.DropDownListFor(p => p.selectedEType, Model.eType.Select(p => new SelectListItem() { Text = p.Value.ToString(), Value = p.Key.ToString(), Selected = false }), new { @class = "form-control", @style = "width:210px", @onchange = "checkaddnew();" })
            </div>
            @Html.ValidationMessageFor(model => model.eType, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Location, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextAreaFor(model => model.Location, new { @style = "width:300px;", @class = "form-control", @rows = "3" })
            @Html.ValidationMessageFor(model => model.Location, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.eventsImage, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input name="imageFile" id="File" type="file" />
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-info" />

            @Html.ActionLink("Back to List", "Index", "Festival", null, new { @class = "btn btn-danger" })
        </div>
    </div>
</div>
}

@Html.Partial("CreateEventType", new MyFestival.Models.EventTypeVM())


@section Scripts {
@Scripts.Render("~/bundles/jqueryval")

<script>
    $(document).ready(function () {
        $('#selectedEType').change(function () {
            if ($(this).find(":selected").val() == -1) {
                $('#myModal').modal('show');
            }
        });
    });
</script>

<script type="text/javascript">
    function ajaxResponse(data) {
        alert("This Worked and the Data ID is: " + data.EventTypeID);
        var newOption = "<option value='" + data.EventTypeID + "'>" + data.Name + "</option>";
        $('#selectedEType').append(newOption);
        $('#myModal').modal('hide');

        $("#selectedEType option[value='" + data.EventTypeID + "']").attr("selected", "selected");
    };
</script>

<script type="text/javascript">
    $(document).ready(function () {
        $("#eventsDate").datepicker('setDate', '+1',{dateFormat: "dd/mm/yy"}).on('changeDate', function (ev) {
            $(this).blur();
            $(this).datepicker('hide');
        });
    });
</script>

<script type="text/javascript">
    $('#startTime').timepicker({
        minuteStep: 5,
        showInputs: false,
        disableFocus: true
    });
</script>

    <script type="text/javascript">
        $('#endTime').timepicker({
            minuteStep: 5,
            showInputs: false,
            disableFocus: true
        });
</script>

}
user3564900
  • 25
  • 2
  • 11

1 Answers1

2

in your GET controller, you are setting the festivalID in the model:

EventsVM events = new EventsVM { festivalID = festID };

so in your view's form somewhere (my preference would be beneath your ValidationSummary), add

@Html.HiddenFor(m => m.festivalID)

then you don't need the second parameter in your POST controller:

public ActionResult Create2(EventsVM model)

because the model contains the festivalID, via model.festivalID.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • The id is passed through @Jonesy. but I am still getting an error: An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. – user3564900 Apr 30 '14 at 14:25
  • that sounds like a different problem. Try looking at [this answer](http://stackoverflow.com/questions/7938384/an-error-occurred-while-saving-entities-that-do-not-expose-foreign-key-propertie) and if you can't figure it out, try posting a new question here on SO – Jonesopolis Apr 30 '14 at 14:49