C#Razor尝试从Dropdown

时间:2016-10-17 04:18:09

标签: c# razor

我正在尝试构建一个EF C#Razor应用程序。我继续努力让下拉框[listbox]的选择调用一个名为getRecruiter的路由(带有该值)并将招聘人员文本框更改为招聘人员。

错误说:未捕获的ReferenceError:未定义RecruiterName 如果有人能帮助我,我将非常感激。我正在尝试学习如何使用Razor和C#,并尝试了我能在网上找到的所有内容。

以下是相关代码:

Notes Model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace JOM.Models
{
    public class NotesModel
    {
        [Key]
        public int NotesID { get; set; }

        public int JobID { get; set; }
        public string Recruiter { get; set; }
        public string NoteTitle { get; set; }
        public string NoteData { get; set; }
        public DateTime ActiveDate { get; set; }
    }

    public class JobWithRecruiter
    {
        public int JobID { get; set; }
        public string RecruiterName { get; set; }
    }
}

Notes控制器:

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 JOM.DAL;
using JOM.Models;

namespace JOM.Controllers
{
    public class NotesModelsController : Controller
    {
        private JobsContext db = new JobsContext();

        // GET: NotesModels
        public ActionResult Index()
        {
            IEnumerable<JobModel> jobs = db.Jobs;
            ViewData["jobs"] = jobs;

            return View(db.Notes.ToList());
        }

        // GET: NotesModels/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            NotesModel notesModel = db.Notes.Find(id);
            if (notesModel == null)
            {
                return HttpNotFound();
            }
            return View(notesModel);
        }

        // GET: NotesModels/Create
        public ActionResult Create()
        {
               IEnumerable<JobModel> jobs = db.Jobs;
            ViewData["jobs"] = jobs;

            return View();
        }

        // POST: NotesModels/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 = "NotesID,JobID,Recruiter,NoteTitle,NoteData,ActiveDate")] NotesModel notesModel)
        {
            ViewBag.Jobs =
             from job in db.Jobs
             select job;
            ViewBag.Recruiters =
                from job in db.Jobs
                join note in db.Notes on job.JobID equals note.JobID
                select new JobWithRecruiter { JobID = job.JobID, RecruiterName = note.Recruiter };

            if (ModelState.IsValid)
            {
                db.Notes.Add(notesModel);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(notesModel);
        }

        // GET: NotesModels/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            NotesModel notesModel = db.Notes.Find(id);
            if (notesModel == null)
            {
                return HttpNotFound();
            }
            return View(notesModel);
        }

        // POST: NotesModels/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 = "NotesID,JobID,Recruiter,NoteTitle,NoteData,ActiveDate")] NotesModel notesModel)
        {
            if (ModelState.IsValid)
            {
                db.Entry(notesModel).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(notesModel);
        }

        // GET: NotesModels/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            NotesModel notesModel = db.Notes.Find(id);
            if (notesModel == null)
            {
                return HttpNotFound();
            }
            return View(notesModel);
        }

        // POST: NotesModels/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            NotesModel notesModel = db.Notes.Find(id);
            db.Notes.Remove(notesModel);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

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

备注视图:

@model JOM.Models.NotesModel
    @using JOM.Models;
@{
    ViewBag.Title = "Create";
}

@functions
{
    public string getRecruiter(int jobID)
    {
        if (jobID > 0)
        {
            var j = (IEnumerable<JobWithRecruiter>)ViewBag.Recruiters;
            return j.Where(jo => jo.JobID.Equals(jobID)).First<JobWithRecruiter>().RecruiterName;
        }
        return "No Name Selected";
    }
        }
<h2>Create</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Notes</h4>
        <hr />
        @{
            int selectedJobID = 0;
            string RecruiterName = "Not Selected";
    }
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            <label class="control-label col-md-2" for="JobDesc">Choose Job:</label>
            <div class="col-md-10">
@{ 
    var jobs = (IEnumerable<JobModel>)ViewBag.Jobs;
    }
    @Html.DropDownList("listbox", jobs.Select(item => new SelectListItem
{
    Value = item.JobID.ToString(),
    Text = item.JobDesc.ToString()
}))

                <script language="Javascript">
    $(document).ready(function () {
        $('#listbox').change(function () {
            selectedJobID = $(this).val();
            @{
                RecruiterName = getRecruiter(selectedJobID); 
                }
            $('#recruiter').val(RecruiterName);

        });
    });
                 </script>
               </div>
        </div>

        <div class="form-group">
            @Html.Label("Recruiter", htmlAttributes: new {@class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBox(RecruiterName, RecruiterName,new { ID="recruiter", @class = "form-control" });
                @Html.ValidationMessageFor(model => model.Recruiter, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

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

@section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
}

2 个答案:

答案 0 :(得分:0)

你不能像调用JS代码一样调用C#代码,所以这个

$(document).ready(function () {
    $('#listbox').change(function () {
        selectedJobID = $(this).val();
        @{
            RecruiterName = getRecruiter(selectedJobID); 
            }
        $('#recruiter').val(RecruiterName);

    });
});
当您更改RecruiterName = getRecruiter(selectedJobID);下拉列表的值时,

并不代表#listbox

您可以做的是准备包含控制器内所有招聘人员的JSON集合并将其传递给您的视图。然后,您只能使用JS(可以像您尝试使用C#代码一样使用)来根据ID检索招聘人员名称。

答案 1 :(得分:0)

在控制器调用列表中:

      [HttpPost]
    public ActionResult bindCityList(int stateid)
    {
        List<SelectListItem> lstcity = new List<SelectListItem>();
        try
        {
            Panel cs = new Panel();
            DataTable dt = new DataTable();
            dt = cs.getCityVsState(Conn, stateid);
            foreach (System.Data.DataRow dr in dt.Rows)
            {
                lstcity.Add(new SelectListItem { Text = @dr["CityName"].ToString(), Value = @dr["CityID"].ToString() });
            }
        }
        catch (Exception ex)
        {
            logger.WriteErrorToFile("Panel::bind City List :" + ex.Message.ToString());

        }
        finally
        {
            Conn.Close();
        }
        return Json(lstcity.AsEnumerable());
    }

在视野中 - 关于状态下拉绑定城市列表的更改

  $('#ddlstate').change(function () {
        var url = "bindCityList";
        $.ajax({
            url: url,
            data: { stateid: $('#ddlstate').val() },
            cache: false,
            type: "POST",
            success: function (data) {
                $("#ddlcity").empty();
                var markup = "<option value='0'>---Select---</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value='" + data[x].Value + "'>" + data[x].Text + "</option>";
                }

                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });
    });