从直接页而不是从标签页

时间:2018-11-20 18:45:22

标签: asp.net-mvc asp.net-mvc-5

第一次在这里发布,我不会以此为借口没有帮助,但这真让我发疯。我是一个完全菜鸟,这不是硬件,但这是我第一次使用asp.net mvc进行的项目(在家/娱乐)。

所以我们开始..

我的主菜单看起来像这样。

@{
    ViewBag.Title = "Index";
}

<ul class="nav nav-tabs">
    <li class="active"><a data-toggle="tab" href="#firstTab">View All 
Vendors</a></li>
    <li><a data-toggle="tab" href="#secondTab">Add New</a></li>
    <li><a data-toggle="tab" href="#thirdTab">Remove</a></li>
</ul>
<div class="tab-content">
    <div id="firstTab" class="tab-pane fade in active">@Html.Action("ViewAll")</div>
    <div id="secondTab" class="tab-pane fade in">@Html.Action("AddOrEdit")</div>
    <div id="thirdTab" class="tab-pane fade in">tab 3 content</div>
</div>
@section scripts
{
    @Scripts.Render("~/bundles/jqueryval")
}

如果我直接运行AddOrEdit.cshtml,我可以进行“ POST”操作。

@model VendorApp.Models.VENDOR

@{
    ViewBag.Title = "AddOrEdit";
}

@using (Html.BeginForm("AddOrEdit","Vendor",FormMethod.Post, new { enctype = "multipart/form-data", onSubmit = "return jQueryAjaxPost(this);" }))
{
    @Html.AntiForgeryToken()
    <div class="row">
        <div class="form-horizontal">
            <h4>Add Vendor</h4>
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor(model => model.VENDOR_NUM)

            <div class="col-md-6">
            <div class="form-group">
                @Html.LabelFor(model => model.VENDOR_NAME, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.VENDOR_NAME, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.VENDOR_NAME, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.STREET, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.STREET, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.STREET, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.CITY, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.CITY, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.CITY, "", new { @class = "text-danger" })
                </div>
            </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.STATE, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.STATE, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.STATE, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Update" class="btn btn-default" />
                    </div>
                </div>
            </div>  
            <div class="col-md-6">
                <div class="form-group">
                    @Html.LabelFor(model => model.ZIP, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.ZIP, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.ZIP, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.PHONE, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.PHONE, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.PHONE, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.EMAIL, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.EMAIL, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.EMAIL, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.SERVICE, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.SERVICE, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.SERVICE, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.NOTE, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.NOTE, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.NOTE, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>    
        </div>
    </div>
}

这是我的控制器

using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VendorApp.Models;

namespace VendorApp.Controllers
{
    public class VendorController : Controller
    {
        // GET: Vendor
        public ActionResult Index()
        {
            return View();
        }

        //get all Vendors
        public ActionResult ViewAll()
        {
            return View(GetAllVendor());
        }

        //numerate the vendors

        IEnumerable<VENDOR>GetAllVendor()
        {
            using (Pref_VendorEntities db = new Pref_VendorEntities())
            {
                return db.VENDORs.ToList<VENDOR>();
            }
        }

        /// <summary>
        /// HTTP GET by DEFAULT
        /// </summary>
        /// <returns></returns>
        public ActionResult AddOrEdit()
        {
            VENDOR vendor = new VENDOR();
            return View(vendor);
        }

        /// <summary>
        /// HTTP Post
        /// </summary>
        /// <returns></returns>

        [HttpPost]
        public ActionResult AddOrEdit(VENDOR vend)
        {
            using (Pref_VendorEntities db = new Pref_VendorEntities())
            {
                db.VENDORs.Add(vend);
                db.SaveChanges();
            }

            return RedirectToAction("ViewAll");
        }
    }
}

如果我直接从index.cshtml调试或加载,我将得到 This

但是,如果我单击“添加新”标签,它看起来像这样。 Add New很好,但是实际上并没有“发布”数据。

如果我直接加载from this page,则页面显示为such

但是实际上它会让我“发布”数据。我希望我提供了足够的信息,但又不过分,不足为奇。我试图在这里四处张望,但我不知道我在做什么错。任何帮助将不胜感激,我将非常乐于详细说明其他要求。

谢谢你!

1 个答案:

答案 0 :(得分:0)

这是东西。您正在将jQuery和MVC结合在一起,并通过AJAX发布。很好,但是您必须将其连接起来(jQuery部分)。

onSubmit = "return jQueryAjaxPost(this);"格式查看您的代码(删除此代码)

使用Ajax很棒,但是必须正确完成,然后必须处理序列化以及两端的所有部分。足够容易,但确实会增加表单的一点点复杂性-不使用回发等。

注意:您正在执行“更新”和“创建”操作。更新可能需要一个ID,因此这是一种实现方法-作为数据属性。

因此,在控制器中创建一个公共方法。让我们称它为SaveVendor-默认情况下通常为“保存”,但针对您的“非默认”情况而定。

创建两个模型(可能是基本模型),一个模型的ID为vendorId,另一个没有ID,我们可以在过载时使用它。

我使用您的VENDOR类,但建议改名为Vendor

public ActionResult SaveVendor(VENDOR vendor)

添加适当的属性:(就像您拥有的一样!)

[HttpPost]
public ActionResult SaveVendor(VENDOR vendor)

现在,这个有供应商ID,因此:(用于更新或添加)

[HttpPost]
public ActionResult SaveVendor(VendorWithId vendor)

在其周围放置一些ajax:注意呈现要更新的表单时,请将ID放入data-vendorid

因此,这有两个按钮,一个用于更新,一个用于在表单中创建。有很多方法可以通过一个按钮来执行此操作,更改文本等。但是为此,我选择在每个按钮上创建两个具有一个类的类,然后进行处理,并显示如何检测到该情况,并在您添加厂商ID时添加其他数据渲染它,得到它,依此类推。

作为练习,我将保留如何处理显示哪个按钮的练习,但是您可以添加一个类(隐藏)或使用代码$('.update').toggle(false);等。

// attach click handler to form, then each button has one
$('#AddOrEdit').on('click', '.create .update', function(event) {
  $(this).preventDefault(); // prevent submit because of button type
  let myform = $(event.delegateTarget);
  let mybuttonType = $(this).hasClass('create') ? "create" : "update";
  //add extra data so we know which
  myform.trigger("submit", ["submitbutton", mybuttonType]);
});
// I assume form ID AddOrEdit here:
$('#AddOrEdit').on('submit', function(event, param1, param2) {
  let myform = $(this);
  let myaction = myform.attr('action');
  let myData = myform.serializeArray();
  if (param2 === "update") {
    let $id = myform.data("vendorid");
    myData.push({
      name: "vendorId",
      value: $id
    });
  }
  $.ajax({
    type: "POST",
    url: myaction,
    data: $.param(myData);
  }).done(function(data) {
    alert(data);
  }).fail(function() {
    // ajax failed, do something
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="AddOrEdit" action="SaveVendor" data-vendorid="23223">
  <button type="submit" class="update btn btn-default">Update</button>
  <button type="submit" class="create btn btn-default">Create</button>
  <div>all my other form elements here:</div>
</form>

注意:我有param1的“ submitbutton”,我这样做只是为了说明如何在事件中使用trigger传递参数,可以随意更改或修改,这只是一个示例。