簡體   English   中英

如何將ListBoxFor值保存到MVC5中的數據庫

[英]How to save ListBoxFor Values to database in MVC5

我想將所有listBoxFor值保存到數據庫...在發布表單時出現此錯誤,提示“對象未設置為對象的瞬時值”,有人可以幫助我找出問題所在嗎?

這是所有的代碼

這是包含所有值的列表框代碼:

@Html.ListBoxFor(model => model.SelectedRecipientId, new MultiSelectList(Model.Recipients, "ID", "RecipientNumbers"), new { id = "recipientList", style = "width: 250px; height: 160px;", name = "recipientList" })

這是我的View模型

public class SendViewModel
{
    public SendViewModel()
    {
        ScheduledDate = DateTime.Now;
    }

    public int Id { get; set; }
    public string Message { get; set; }
    public DateTime ScheduledDate { get; set; }

    public IEnumerable<SelectListItem> Times { get; set; }
    public string[] SelectedRecipientId { get; set; }

    [Required]
    public IEnumerable<SelectListItem> Recipients { get; set; }
}

這是我要寫的模型

public class SentMessage
{
    public int Id { get; set; }
    public string Message { get; set; }
    public string SenderId { get; set; }
    public DateTime SendDate { get; set; }
    public int RecipientCount { get; set; }
    ...

    public virtual ICollection<MessageRecipient> Recipients { get; set; }
}

這是我的后控制器

if (ModelState.IsValid)
{
    if (model.ScheduledDate == DateTime.Now)
    {
        _messageService.SendMessage(User, SenderId, model.Message, model.SelectedRecipientId);

        return Redirect("/UserAccount/SendMessageConfirmation");
    }
}

最后是消息服務參數集合

int SendMessage(int userId, string senderId, string message, IEnumerable<string> recipients);

這是將所有數據從視圖保存到數據庫的簽名,而IEnumerable<string> recipients是負責從列表框中獲取所有值的參數。

我該怎么做,以便它將能夠保存到數據庫。

這是錯誤堆棧跟蹤

Server Error in '/' Application.

你調用的對象是空的。

說明:執行當前Web請求期間發生未處理的異常。 請查看堆棧跟蹤,以獲取有關錯誤及其在代碼中起源的更多信息。

異常詳細信息:System.NullReferenceException:對象引用未設置為對象的實例。

源錯誤:

行68:行69: 收件人行70:@ Html.ListBoxFor(model => model.SelectedRecipientId,新的MultiSelectList(Model.Recipients,“ ID”,“ RecipientNumbers”),新的{id =“ recipientList”,樣式=“寬度:250px;高度:160px;“,名稱=” SelectedRecipientId“})第71行:第72行:

源文件:c:\\ Development \\ Projects \\ SMSXChange \\ SmsXchange \\ XChange.MVC \\ Views \\ Message \\ Send.cshtml行:70

堆棧跟蹤:

[NullReferenceException:對象引用未設置為對象的實例。] ASP._Page_Views_Message_Send_cshtml

感謝您提供錯誤詳細信息,

盡管我在評論中提到的事情是正確的,“ HTML Element Name ”和“ Model Property Name ”都應該與發布值相似,但此處的問題與您得到的錯誤有所不同。

在渲染視圖之前,請確保正確填充了Model.Recipients屬性。 您從調用視圖的位置開始的操作應為Model.Recipients屬性分配正確的值。 您的屬性為null,因此會引發對象引用錯誤。

實際上,該錯誤應該出現在表單的初始加載上,而不是發布之后。 如果仍然在發布表單后到來,則存在以下可能性。 當您添加ModelState.IsValid檢查后,這似乎並不令人滿意,並且存在一些驗證錯誤,這導致Post操作方法再次呈現相同的視圖(提供者,您在其他部分沒有執行其他任何操作)再次加載,因為您沒有在post方法中添加該代碼,所以沒有填寫選擇列表。 因此,可能的解決方案是,如果存在任何驗證錯誤,則在POST操作中再次填充Model.Recipients 我希望你明白我的意思

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM