繁体   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