簡體   English   中英

在asp.net MVC的一個頁面上有多個帖子,具有部分視圖

[英]Multiple posts on a single page asp.net MVC with partial views

我們有一個頁面,當前包含四個或五個局部視圖,但是這個頁面可能會增長。 目前,針對兩個完全不同的數據庫功能,有兩個POST操作。

如果我們嘗試在另一個對象上執行create函數,則重定向將導致“對象引用未設置為對象的實例”。 錯誤,這與另一個POST局部視圖有關。

有辦法阻止這種情況嗎? 從本質上講,在我看來,一個局部視圖的帖子正在嘗試與另一個視圖交互。 有任何想法嗎?

謝謝

用於創建的公告控制器:

[HttpPost]
        public ActionResult CreateMain(BulletinsViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                BulletinsContext.tblBulletins.Add(new tblBulletin
                {
                    ID = viewModel.BulletinID,
                    BulletinDisplayDate = viewModel.BulletinDisplayDate,
                    BulletinFilename = viewModel.MainBulletinName,
                    IsSixthForm = viewModel.IsSixthForm                    
                });

                //For loop to delete bulletins
                //If bulletin folder has more than 10 files in
                //Delete the oldest file, itererate till only 10 remain   
                {
                    DirectoryInfo dir = new DirectoryInfo(@"D:\Inetpub\WWWroot\intranet\Dashboard\Dashboard\Files\Bulletins");
                    List<FileInfo> filePaths = dir.GetFiles().OrderByDescending(p => p.CreationTime).ToList();
                    for (int index = filePaths.Count() - 1; index > 9; index--)
                    {
                        var fileNames = filePaths[index].Name;
                        //Delete from directory
                        filePaths[index].Delete();


                        //Remove from collection to restart the loop
                        filePaths.RemoveAt(index);

                    }
                }

                //Save changes to database
                BulletinsContext.SaveChanges();

                //Return to main bulletins index page
                return RedirectToAction("~/Home/Index");
            }

            return View(viewModel);
        }

公告創建視圖:

@model Dashboard.Viewmodels.BulletinsViewModel

@{
    ViewBag.Title = "Create";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.BulletinDisplayDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BulletinDisplayDate, new { htmlAttributes = new { @class = "form-control", @id = "datepicker-basic", @readonly = "readonly" } })
                @Html.ValidationMessageFor(model => model.BulletinDisplayDate, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.MainBulletinName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="input-group">
                    @Html.EditorFor(model => model.MainBulletinName, new { htmlAttributes = new { @class = "form-control", @Value = "Select File...", @readonly="readonly" } })
                    <span class="input-group-addon" href="javascript:;" onclick="moxman.browse({ fields: 'MainBulletinName', extensions: 'pdf', path: 'D:/Inetpub/WWWroot/intranet/Dashboard/Dashboard/Files/Bulletins' });" style="cursor: pointer;"><i class="fa fa-upload"></i></span>
                        @Html.ValidationMessageFor(model => model.MainBulletinName, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>



    </div>


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

}


<script type="text/javascript" src="~/Scripts/tinymce/plugins/moxiemanager/js/moxman.loader.min.js"></script>

打印機信用創建控制器:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult PrinterCredits(PrinterCreditsViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                //Send the email if credits are added..
                //Create a bunch of variables for the email
                //Create the email body etc

                var fromAddress = "";
                string toName = Request.Form["Username"].ToUpper();
                string AmountOfCredits = Request.Form["AmountAdded"];
                string Plural = "";
                string Title = "";
                string AddedByWho = User.Identity.Name.Split('\\')[1];
                System.DateTime AddedWhen = DateTime.Now;
                if (AmountOfCredits == "1")
                {
                    Plural = " printer credit has ";
                    Title = "Printer Credit Added!";
                }
                else
                {
                    Plural = " printer credits have ";
                    Title = "Printer Credits Added!";
                }
                var toEmail = toName + "";
                var subject = AmountOfCredits + Plural + "been added to your account, " + toName;
                string body = "";

                //Create an SMTP client for sending an email
                var smtp = new SmtpClient
                {
                    Host = "",
                    Port = 25,
                    EnableSsl = false,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = true,
                };

                //Populate the SMTP client and encode the body for the HTML
                using (var message = new MailMessage(fromAddress, toEmail)
                {
                    Subject = subject,
                    Body = body,
                    IsBodyHtml = true,
                    BodyEncoding = System.Text.Encoding.UTF8
                })

                    //Try to send the email. If sent, insert data.
                    //Redirect back to original page
                    //Take current printer credit from and update with fund + cost

                    try
                    {
                        //Link the viewmodel and the database together
                        PartialViewContext.tblPrinterCredits.Add(new tblPrinterCredit
                        {
                            Username = viewModel.Username,
                            AmountAdded = viewModel.AmountAdded,
                            AddedBy = AddedByWho,
                            AddedWhen = viewModel.AddedWhen,
                            Money = viewModel.AmountAdded * 0.02
                        });


                        Nullable<double> cost = viewModel.AmountAdded * 0.02;

                        //Update the printer credit fund and insert into tblOption
                        tblOption fund = (
                            from n in PartialViewContext.tblOptions
                            where n.ID == 1
                            select n).First();
                        fund.PrinterCreditFund = fund.PrinterCreditFund + cost;


                        PartialViewContext.SaveChanges();
                        message.CC.Add("");
                        smtp.Send(message);

                        Response.Redirect("~/Home/Index");
                    }
                    //If it fails, go chicken oriental (only a redirect, will eventually become a crazy message)
                    catch
                    {
                        smtp.Send(message);
                        Response.Redirect("~/Home/Index");
                    }
            }
            return View(viewModel);

打印機積分視圖:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()


        <div class="panel">
            <div class="panel-heading">
                <span class="panel-icon">
                    <i class="fa fa-print"></i>
                </span>
                Add Printer Credits - @Costings
            </div>
            <div class="panel-body">
                <div class="form-horizontal">
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <div class="form-group">
                        <label class="control-label col-md-3">User:</label>
                        <div class="col-xs-8">
                            @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control", @id = "Username", @name = "Username", @maxlength = "6" } })
                            @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label col-md-3">Amount:</label>
                        <div class="col-xs-8">
                            @Html.EditorFor(model => model.AmountAdded, new { htmlAttributes = new { @class = "form-control", @id = "AmountAdded", @onkeyup = "Update()", @Value = 0 } })
                            @Html.ValidationMessageFor(model => model.AmountAdded, "", new { @class = "text-danger", @type="number" })
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label col-md-3">Cost:</label>
                        <div class="col-xs-8">
                            @Html.EditorFor(model => model.TotalCost, new { htmlAttributes = new { @class = "form-control", @id = "TotalCost", @readonly = "readonly", @Value = "0" } })
                            @Html.ValidationMessageFor(model => model.TotalCost, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-md-offset-1 col-md-10">
                            <input type="submit" value="Add Printer Credits" class="btn btn-primary btn-gradient dark btn-block" />
                            @Html.EditorFor(model => model.AddedBy, new { htmlAttributes = new { @class = "form-control", @Value = User.Identity.Name.Split('\\')[1], @Style = "display: none;" } })
                            @Html.ValidationMessageFor(model => model.AddedBy, "", new { @class = "text-danger" })
                        </div>
                    </div>

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

}

<script type="text/javascript">
    $(document).ready(
        function () {
            Update();
            $('#AmountAdded, #TotalCost')
        .keyup(function () {
            Update();
        })
        }
        );

    function Update() {
        var cost = 2
        var one = $('#AmountAdded'),
            two = $('#TotalCost');
        two.val(parseInt(one.val()) * cost / 100);
    }

</script>

<script type="text/javascript">
    document.getElementById('Username').focus()
</script>

只是弄清楚了我需要告訴表單要使用哪個操作和控制器,盡管事實上有兩個不同的控制器正在運行視圖。 但是無論如何,一個例子是:

@using (Html.BeginForm("CreateMain", "Bulletins", FormMethod.Post, new { }))

暫無
暫無

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

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