c# Razor尝试从下拉菜单中填充文本框
本文关键字:填充 文本 下拉菜单 Razor | 更新日期: 2023-09-27 18:13:15
我正在尝试构建一个EF c# Razor应用程序。我继续尝试让下拉框[listbox]的选择调用一个名为getRecruiter的路由(带有该值),并将招聘人员名称文本框更改为招聘人员。
它错误地说:Uncaught ReferenceError: recruittername未定义如果有人能帮助我,我将不胜感激。我正在努力学习如何使用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);
}
}
}
Notes视图:
@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")
}
你不能调用c#代码,如果它是JS代码,所以这个
$(document).ready(function () {
$('#listbox').change(function () {
selectedJobID = $(this).val();
@{
RecruiterName = getRecruiter(selectedJobID);
}
$('#recruiter').val(RecruiterName);
});
});
并不意味着当你改变#listbox
的值时,RecruiterName = getRecruiter(selectedJobID);
将被分配。
你可以做的是准备JSON集合包含所有你的招聘人员在控制器和传递给你的视图。然后你可以只使用JS(它会像你尝试使用c#代码一样工作)来检索基于ID的招聘人员名称。
在控制器调用列表:
[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());
}
In view——更改状态下拉绑定城市列表
$('#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);
}
});
});