Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 一页asp.net MVC上的多篇文章,带有部分视图_C#_Asp.net_Asp.net Mvc_Asp.net Mvc 4 - Fatal编程技术网

C# 一页asp.net MVC上的多篇文章,带有部分视图

C# 一页asp.net MVC上的多篇文章,带有部分视图,c#,asp.net,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,我们有一个页面,目前包含四到五个部分视图,但可能会增长。目前,有两个POST操作,用于两个完全不同的数据库函数 如果我们尝试在另一个上执行create函数,重定向将导致“对象引用未设置为对象的实例”错误,这将与另一个POST partial视图相关 有没有办法阻止这一切?本质上,在我看来,一个局部视图的帖子试图与另一个交互。有什么想法吗 谢谢 用于创建的公告控制器: [HttpPost] public ActionResult CreateMain(BulletinsViewMo

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

如果我们尝试在另一个上执行create函数,重定向将导致“对象引用未设置为对象的实例”错误,这将与另一个POST partial视图相关

有没有办法阻止这一切?本质上,在我看来,一个局部视图的帖子试图与另一个交互。有什么想法吗

谢谢

用于创建的公告控制器:

[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);
        }
[HttpPost]
公共操作结果CreateMain(BulletinsViewModel视图模型)
{
if(ModelState.IsValid)
{
BulletinsContext.tblBulletins.Add(新的tblBulletin
{
ID=viewModel.BulletinID,
BulletinPlayDate=viewModel.BulletinPlayDate,
BulletinFilename=viewModel.MainBulletinName,
IsSixthForm=viewModel.IsSixthForm
});
//用于删除公告的循环
//如果公告文件夹中的文件超过10个
//删除最旧的文件,直到只剩下10个
{
DirectoryInfo dir=new DirectoryInfo(@“D:\Inetpub\WWWroot\intranet\Dashboard\Dashboard\Files\Bulletins”);
List filepath=dir.GetFiles().OrderByDescending(p=>p.CreationTime).ToList();
对于(int index=filepath.Count()-1;索引>9;索引--)
{
var fileNames=filepath[index].Name;
//从目录中删除
文件路径[index].Delete();
//从集合中删除以重新启动循环
filepath.RemoveAt(索引);
}
}
//将更改保存到数据库
BulletinsContext.SaveChanges();
//返回主公告索引页
返回重定向到操作(“~/Home/Index”);
}
返回视图(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>
@model Dashboard.Viewmodels.BulletinsViewModel
@{
ViewBag.Title=“创建”;
}
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true,“,new{@class=“text danger”})
@LabelFor(model=>model.bulletinsplaydate,htmlAttributes:new{@class=“controllabel col-md-2”})
@EditorFor(model=>model.bulletinsplaydate,new{htmlAttributes=new{@class=“form control”,@id=“datepicker basic”,@readonly=“readonly”})
@Html.ValidationMessageFor(model=>model.BulletinPlayDate,“,new{@class=“text danger”})
@LabelFor(model=>model.mainbertinname,htmlAttributes:new{@class=“controllabel col-md-2”})
@EditorFor(model=>model.mainbertinname,new{htmlAttributes=new{@class=“form control”,@Value=“Select File…”,@readonly=“readonly”})
@Html.ValidationMessageFor(model=>model.mainbertinName,“,new{@class=“text danger”})
}
打印机信用创建控制器:

[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);
[HttpPost]
[ValidateAntiForgeryToken]
公共操作结果PrinterCredits(PrinterCreditsViewModel视图模型)
{
if(ModelState.IsValid)
{
//如果添加了信用卡,请发送电子邮件。。
//为电子邮件创建一组变量
//创建电子邮件正文等
var fromAddress=“”;
字符串toName=Request.Form[“Username”].ToUpper();
字符串AmountOfCredits=Request.Form[“AmountAdded”];
字符串复数=”;
字符串标题=”;
字符串AddedByWho=User.Identity.Name.Split('\\')[1];
System.DateTime AddedWhen=DateTime.Now;
如果(AmountOfCredits==“1”)
{
复数=“打印机信用已”;
Title=“已添加打印机信用!”;
}
其他的
{
复数=“打印机信用有”;
Title=“已添加打印机信用证!”;
}
var toEmail=toName+“”;
var subject=AmountOfCredits+复数+“已添加到您的帐户,”+toName;
字符串体=”;
//创建用于发送电子邮件的SMTP客户端
var smtp=新SmtpClient
{
主机=”,
端口=25,
EnableSsl=false,
DeliveryMethod=SmtpDeliveryMethod.Network,
UseDefaultCredentials=true,
};
//填充SMTP客户端并对HTML的正文进行编码
使用(var message=新邮件消息(fromAddress,toEmail)
{
主语,
身体,
IsBodyHtml=true,
BodyEncoding=System.Text.Encoding.UTF8
})
//尝试发送电子邮件。如果已发送,请插入数据。
//重定向回原始页面
//从获取当前打印机贷记,并使用资金+成本进行更新
尝试
{
//将viewmodel和数据库链接在一起
PartialViewContext.tblPrinterCredits.Add(新tblPrint
@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 { }))