单个页面上的多个帖子asp.net MVC具有部分视图

时间:2015-06-22 13:50:58

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我们有一个页面,目前包含四个或五个部分视图,但可能会增长。目前,有两个POST操作,两个完全不同的数据库函数。

如果我们尝试在另一个上执行create function,则重定向会导致“对象引用未设置为对象的实例”。错误,然后与其他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>

1 个答案:

答案 0 :(得分:0)

尽管有两个不同的控制器正在运行视图,但我还是想知道我需要告诉表单使用哪个动作和控制器。但无论如何,一个例子是:

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