将 Id 从一个控制器传递到另一个控制器

Posted

技术标签:

【中文标题】将 Id 从一个控制器传递到另一个控制器【英文标题】:Passing an Id from one controller to another 【发布时间】:2014-04-30 13:50:12 【问题描述】:

您好,我的 mvc 4 应用程序中有这个。一旦您向系统添加了一个节日,我想通过传递一个 id 向该节日添加一个事件。谁能帮我?这是我的控制器以及我的视图、视图模型和模型。我收到一个错误:

参数字典包含“MyFestival”中方法“System.Web.Mvc.ActionResult Create2(MyFestival.Models.EventsVM, Int32)”的不可为空类型“System.Int32”的参数“festID”的空条目。控制器.EventsController'。可选参数必须是引用类型、可空类型或声明为可选参数。

    [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);
    

这是我的模型

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; 

视图模型

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; 

这是我的观点

@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>


【问题讨论】:

您想通过链接、提交时还是使用 javascript 发送它? 当您单击创建时,我正在尝试将 id 传递到事件表中。 【参考方案1】:

在您的 GET 控制器中,您正在模型中设置节日 ID:

EventsVM events = new EventsVM  festivalID = festID ;

所以在您的视图中某处(我的偏好将在您的 ValidationSummary 下方),添加

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

那么您的 POST 控制器中不需要第二个参数:

public ActionResult Create2(EventsVM model)

因为模型包含节日ID,通过model.festivalID

【讨论】:

id 是通过@Jonesy 传递的。但我仍然收到一个错误:保存不为其关系公开外键属性的实体时发生错误。 EntityEntries 属性将返回 null,因为无法将单个实体标识为异常源。通过在实体类型中公开外键属性,可以更轻松地处理保存时的异常。 这听起来像是一个不同的问题。尝试查看this answer,如果您无法弄清楚,请尝试在 SO 上发布一个新问题

以上是关于将 Id 从一个控制器传递到另一个控制器的主要内容,如果未能解决你的问题,请参考以下文章

在 RAILS 中将模型从一个控制器动作传递到另一个控制器动作的替代方法

将数据从视图控制器传递到另一个视图控制器

快速将图像从一个视图控制器传递到另一个视图控制器

将变量从页面视图控制器传递到另一个

将数据从 viewcontroller tableview 传递到另一个视图控制器

将 ImageData 从一个视图控制器传递到另一个视图控制器