2016-10-17 2 views
1

EF C# Razor 응용 프로그램을 빌드하려고합니다. 드롭 다운 상자 [listbox]의 선택 항목에 getRecruiter (해당 값 포함)라는 경로를 호출하고 recruitername 텍스트 상자를 신입 사원으로 변경하는 데 계속 실패하고 있습니다.드롭 다운에서 텍스트 상자를 채우는 C# Razor

오류 : Uncaught 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; } 
    } 
} 

주 컨트롤러 :

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") 
} 

답변

0

당신이 JS 코드 인 경우 같은 C# 코드를 호출 할 수 없습니다 여기

는 관련 코드 이므로이

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

    }); 
}); 

#listbox 값을 변경할 때 RecruiterName = getRecruiter(selectedJobID);이 할당된다는 것을 의미하지 않습니다.

컨트롤러 내에서 모든 채용 담당자가 포함 된 JSON 컬렉션을 준비하고보기에 전달할 수 있습니다. 그런 다음 JS (C# 코드로 시도한 것처럼 작동합니다) 만 사용하여 ID를 기반으로하는 채용 담당자 이름을 검색 할 수 있습니다. 컨트롤러 호출 목록에서

+0

의 변화에, 감사합니다. – user7029028

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); 
      } 
     }); 
    }); 
관련 문제