将字符串发送到Action并获取Json Resualt

时间:2016-06-21 11:04:23

标签: jquery ajax asp.net-mvc

我是jquery和ajax的初学者。 我有一个操作可以检索我的数据,我想通过ajax访问此操作。

我的行动:

public JsonResult FillSubject(string GroupServiceID)
{
    //string GSID = GroupServiceID.Substring(1, (GroupServiceID.Length)-2);
    var Subjects = db.Subjects.Where(c => c.GroupServicesID.ToString() == GroupServiceID);
    var SubjectList = Subjects.Select(sl => new SubjectList { ID = sl.ID, GroupServiceID = sl.GroupServicesID, strSubjectName = sl.strSubjectName });
    return Json(SubjectList);
}

和我的jquery(ajax):

<script>
    function FillSubject() {
        var GroupServicesId = $('#GroupServices_ID').val();
        $.ajax({
            url: "Advertisements/FillSubject",
            type: "GET",
            data: { 'GroupServiceID': GroupServicesId },
            success: function (Subjects) {
                $("#Subject_ID").html(""); // clear before appending new list
                $.each(Subjects, function (subject) {
                    $("#Subject_ID").append(
                        $('<option></option>').val(subject.ID).html(subject.strSubjectName));
                });
            },
            error: function (e) {
                alert(this.url);
            },
        });
    }
</script>

我的jquery代码是通过更改我的下拉列表来运行的。 这是我的第一次下拉:

@Html.DropDownListFor(model => model.GroupServices_ID, new SelectList(GroupServicesList, "ID", "strGroupServiceName"), new { @class = "selectpicker", @onchange = "FillSubject()" })

并将结果添加到第二个下拉列表中

@Html.DropDownListFor(model => model.Subject_ID, new SelectList(SubjectsList, "ID", "strSubjectName"), new { @class = "selectpicker" })`

我的操作未收到数据,我的脚本显示错误。

更新1:2016年6月22日

我的控制员:

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

namespace MeydanMvc.Controllers
{
    public class AdvertisementsController : Controller
    {
        private DataBaseContext db = new DataBaseContext();

        // GET: Advertisements
        public ActionResult Index()
        {
            var advertisements = db.Advertisements.Include(a => a.Acting).Include(a => a.Advertiser);
            return View(advertisements.ToList());
        }

        // GET: Advertisements/Details/5
        public ActionResult Details(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Advertisement advertisement = db.Advertisements.Find(id);
            if (advertisement == null)
            {
                return HttpNotFound();
            }
            return View(advertisement);
        }

        // GET: Advertisements/Create
        public ActionResult Create()
        {
            ViewBag.ID = new SelectList(db.Acting, "Advertisement_ID", "strFieldOfStudy");
            ViewBag.ID = new SelectList(db.Advertiser, "ID", "strName");
            ViewBag.GroupServices = db.GroupServices.ToList();
            ViewBag.Subjects = db.Subjects.ToList();
            return View();
        }
        public IList<Subject> GetSubject(Guid GroupSrvicesID)
        {
            return db.Subjects.Where(m => m.GroupServicesID == GroupSrvicesID).ToList();
        }

        public JsonResult GetJsonSubject(Guid GroupSrvicesID)
        {

            var subjectListt = this.GetSubject(GroupSrvicesID);
            var subjectList = subjectListt.Select(m => new SelectListItem()
            {
                Text = m.strSubjectName,
                Value = m.ID.ToString()
            });

            return Json(subjectList, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        public JsonResult FillSubject(string GroupServiceID)
        {
            //string GSID = GroupServiceID.Substring(1, (GroupServiceID.Length)-2);
            var Subjects = db.Subjects.Where(c => c.GroupServicesID.ToString() == GroupServiceID);
            var SubjectList = Subjects.Select(sl => new SubjectList { ID = sl.ID, GroupServiceID = sl.GroupServicesID, strSubjectName = sl.strSubjectName });
            return Json(SubjectList,JsonRequestBehavior.AllowGet);
        }
        public ActionResult Test(int id)
        {
            string message = "سلام";
            if(id==0)
            {
                return Json(message, JsonRequestBehavior.AllowGet);
            }
            else
            {
                message = "خداحافظ";
                return Json(message, JsonRequestBehavior.AllowGet);
            }
        }
        // POST: Advertisements/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,strAdvertisementTitle,dtStartDate,dtEndDate,tsStartTime,tsEndTime,Discription,iWage,iPhoneNumber1,iPhoneNumber2,strEmail,bOccasion,IsActive,InsertTime,UpdateTime,IsDeleted,DeletedTime")] Advertisement advertisement)
        {
            if (ModelState.IsValid)
            {
                advertisement.ID = Guid.NewGuid();
                db.Advertisements.Add(advertisement);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ID = new SelectList(db.Acting, "Advertisement_ID", "strFieldOfStudy", advertisement.ID);
            ViewBag.ID = new SelectList(db.Advertiser, "ID", "strName", advertisement.ID);
            return View(advertisement);
        }

        // GET: Advertisements/Edit/5
        public ActionResult Edit(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Advertisement advertisement = db.Advertisements.Find(id);
            if (advertisement == null)
            {
                return HttpNotFound();
            }
            ViewBag.ID = new SelectList(db.Acting, "Advertisement_ID", "strFieldOfStudy", advertisement.ID);
            ViewBag.ID = new SelectList(db.Advertiser, "ID", "strName", advertisement.ID);
            return View(advertisement);
        }

        // POST: Advertisements/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,strAdvertisementTitle,dtStartDate,dtEndDate,tsStartTime,tsEndTime,Discription,iWage,iPhoneNumber1,iPhoneNumber2,strEmail,bOccasion,IsActive,InsertTime,UpdateTime,IsDeleted,DeletedTime")] Advertisement advertisement)
        {
            if (ModelState.IsValid)
            {
                db.Entry(advertisement).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ID = new SelectList(db.Acting, "Advertisement_ID", "strFieldOfStudy", advertisement.ID);
            ViewBag.ID = new SelectList(db.Advertiser, "ID", "strName", advertisement.ID);
            return View(advertisement);
        }

        // GET: Advertisements/Delete/5
        public ActionResult Delete(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Advertisement advertisement = db.Advertisements.Find(id);
            if (advertisement == null)
            {
                return HttpNotFound();
            }
            return View(advertisement);
        }

        // POST: Advertisements/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(Guid id)
        {
            Advertisement advertisement = db.Advertisements.Find(id);
            db.Advertisements.Remove(advertisement);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

和我的观点

@model MeydanMvc.Models.Advertisement

@{
    Layout = null;
    var GroupServicesList = ViewBag.GroupServices as IEnumerable<MeydanMvc.Models.GroupServices>;
    var SubjectsList = ViewBag.Subjects as IEnumerable<MeydanMvc.Models.Subject>;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
    <link href="~/Content/bootstrap-select.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />

    <script src="~/Scripts/jquery-2.0.0.min.js"></script>
    <script>

    function FillSubject() {

        var GroupServicesId = $('#GroupServices_ID').val();
        $.ajax({
            url: "/Advertisements/FillSubject",
            type: "GET",
            data: { 'GroupServiceID': GroupServicesId },
            dataType:"json",
            success: function (Subjects) {
                $("#Subject_ID").html("");
                $.each(Subjects, function (i, subject) {
                    $("#Subject_ID").append($('<option></option>').val(subject.ID).html(subject.strSubjectName));
                });
            },
            error: function (e) {
                alert(this.url);
            }
        });
    }
    </script>


</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Advertisement</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.strAdvertisementTitle, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.strAdvertisementTitle, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.strAdvertisementTitle, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.GroupServices_ID, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(model => model.GroupServices_ID, new SelectList(GroupServicesList, "ID", "strGroupServiceName"), new { @class = "selectpicker", @onchange = "FillSubject()" })
                    @Html.ValidationMessageFor(model => model.GroupServices_ID, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.Subject_ID, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(model => model.Subject_ID, new SelectList(SubjectsList, "ID", "strSubjectName"), new { @class = "selectpicker" })
                    @Html.ValidationMessageFor(model => model.Subject_ID, "", new { @class = "text-danger" })
                </div>
            </div>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>


    <script src="~/Scripts/bootstrap.min.js"></script>
    <script src="~/Scripts/bootstrap-select.min.js"></script>

</body>
</html>

我运行项目,但我的脚本运行错误方法

update 2 2016/6/22

我更改我的控制器并在ajax中提供json结果但不更新我的第二个下拉列表 我的结果 [Object { ID="ffb1d85a-a822-41e1-8859-24db2b5bc72e", GroupServiceID="0cc2cdf6-b9d3-4274-9cc1-31daf5814458", strSubjectName="برنامه نویسی"}, Object { ID="1f65f038-0111-479a-bdf3-d43eb772af9d", GroupServiceID="0cc2cdf6-b9d3-4274-9cc1-31daf5814458", strSubjectName="آموزش زبان خارجه"}]

5 个答案:

答案 0 :(得分:0)

请尝试以下步骤:

更改控制器操作,如下所示:

  public ActionResult SomeActionMethod() {
      //string GSID = GroupServiceID.Substring(1, (GroupServiceID.Length)-2);
        var Subjects = db.Subjects.Where(c => c.GroupServicesID.ToString() == GroupServiceID);
        var SubjectList = Subjects.Select(sl => new SubjectList { ID = sl.ID, GroupServiceID = sl.GroupServicesID, strSubjectName = sl.strSubjectName });
        return Json(SubjectList);
   }                                                  

然后进行以下ajax调用:

     $.getJSON("Advertisements/FillSubject", 
               { 'GroupServiceID':GroupServicesId },
             function(data) {
                alert(data);

          }
      );

答案 1 :(得分:0)

试试这样。

<script>
 $.ajax({
    type: "GET",
    url: "Advertisements/FillSubject",
    contentType: "application/json; charset=utf-8",
    data: { 'GroupServiceID': GroupServicesId },
    dataType: "json",
    success: function (data) {
        var ddlCustomers = $("[id*=Subject_ID]");
        ddlCustomers.empty().append('<option selected="selected" value="0">--Please select--</option>');
        $.each(data, function (i, v) {
            ddlCustomers.append($("<option</option>", { value: v.ID, text: v.strSubjectName}));
        });
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(textStatus + "_" + errorThrown);
    }
});
</script>

答案 2 :(得分:0)

我修改了ajax代码中的一些更改。

.TextFrame.Characters.Font

答案 3 :(得分:0)

首先,在控制器中更改FillSubject操作,如下所示:

return Json(SubjectList,JsonRequestBehavior.AllowGet);

其次,将下面的javascript复制并粘贴到你拥有的内容上。你有一些缺少关闭括号和括号,而你的$.each循环错误:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script>

    function FillSubject() {

        var GroupServicesId = $('#GroupServices_ID').val();
        $.ajax({
            url: "/Advertisements/FillSubject",
            type: "GET",
            data: { 'GroupServiceID': GroupServicesId },
            success: function (Subjects) {
                $("#Subject_ID").html("");
                $.each(Subjects, function (i, subject) {
                    $("#Subject_ID").append($('<option></option>').val(subject.ID).html(subject.strSubjectName));
                });
            },
            error: function (e) {
                alert(this.url);
            }
        });
    }
</script>

答案 4 :(得分:0)

我在这个控制器中创建一个新的控制器并添加动作。我可以在Ajax方法中获得结果但是我无法在下拉列表中显示我的结果因为我使用Bootstrap-select作为样式而这是我的Ajax函数的冲突。我清除了这个组件并正确运行项目