简体   繁体   中英

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

We've got a page which currently contains a four or five partial views, but is something that could grow. At the moment, there's two POST actions, for two entirely different database functions.

If we try doing the create function on another, the redirect then results in an "Object reference not set to an instance of an object." error, which is then relating to the other POST partial view.

Is there a way to stop this? Essentially, it seems to me that the post for one partial view is trying to interact with the other. Any ideas?

Thanks

Bulletins Controller for Creating:

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

Bulletins Create View:

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

Printer Credits Create Controller:

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

Printer Credits View:

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

Just figured out that I need to tell the form which action and controller to use, despite the fact two different controllers are running the views. But anyway, an example is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM