Dropdown list with ajax generated options not saving for CityId property

痞子三分冷 提交于 2021-02-19 10:43:53

问题


I have been trying for three days, but I could not figure out the mistakes because the code is correct, but its implementation is not what I want. i am using three tables State,City and Donator,i want donator to select it's state and city when select state it display the specified city but when save its informatio the cityId don't save as in the image as at the end.

i use ap.net mvc 5 code first.

any one can help and tell me how to solve this problem the following my Models,Controller,and View:

public enum Gender
    { Male, Femal }
    public class Donator
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Gender gender { get; set; }
        public int Age { get; set; }
        public string BloodType { get; set; }
        public int StateId { get; set; }
        public int CityId { get; set; }
        [ForeignKey("StateId")]
        public State state { get; set; }

    }

//State Table
 public class State
    {
        public int StateId { get; set; }
        public string StateName { get; set; }
        public ICollection<City> cities { get; set; }
        public ICollection<Donator> donS { get; set; }
    }

//City table
     public class City
    {
        public int CityId { get; set; }
        public string CityName { get; set; }
        public int StateId { get; set; }
        [ForeignKey("StateId")]
        public State state { get; set; }
    }
//Donators Controller
public class DonatorsController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: Donators
    public ActionResult Index()
    {
        return View(db.Donators.ToList());
    }

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

    // GET: Donators/Create
    public ActionResult Create()
    {
        ViewBag.StateId = new SelectList(db.state, "StateId", "StateName");
        return View();
    }

    // POST: Donators/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Name,gender,Age,BloodType,CountryId,StateId")] Donator donator)
    {
        if (ModelState.IsValid)
        {
            db.Donators.Add(donator);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.StateId = new SelectList(db.state, "StateId", "StateName", donator.StateId);

        return View(donator);
    }

    // GET: Donators/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Donator donator = db.Donators.Find(id);
        if (donator == null)
        {
            return HttpNotFound();
        }

        ViewBag.StateId = new SelectList(db.state, "StateId", "StateName", donator.StateId);
        return View(donator);
    }

    // POST: Donators/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Name,gender,Age,BloodType,StateId,CityId")] Donator donator)
    {

        if (ModelState.IsValid)
        {
            db.Entry(donator).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.CountryId = new SelectList(db.country, "CountryId", "CountryName");
        return View(donator);
    }

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

    // POST: Donators/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Donator donator = db.Donators.Find(id);
        db.Donators.Remove(donator);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    public JsonResult StateList(int Id)
    {
        var state = from s in db.state
                    where s.CountryId == Id
                    select s;
        return Json(new SelectList(state.ToArray(), "StateId", "StateName"), JsonRequestBehavior.AllowGet);
    }

    public JsonResult Citylist(int id)
    {
        var city = from c in db.city
                   where c.StateId == id
                   select c;
        return Json(new SelectList(city.ToArray(), "CityId", "CityName"), JsonRequestBehavior.AllowGet);
    }
    public IList<State> Getstate(int CountryId)
    {
        return db.state.Where(m => m.CountryId == CountryId).ToList();
    }
    [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult LoadClassesByCountryId(string CountryName)
    {
        var stateList = this.Getstate(Convert.ToInt32(CountryName));
        var stateData = stateList.Select(m => new SelectListItem()
        {
            Text = m.StateName,
            Value = m.CountryId.ToString(),
        });
        return Json(stateData, JsonRequestBehavior.AllowGet);
    }

}

//Create View

@model WebApplication6.Models.Donator

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")

    <script type="text/jscript">
    $(function () {
        $('#State').change(function () {
            $.getJSON('/Donators/Citylist/' + $('#State').val(), function (data) {
                var items = '<option>Select a City</option>';
                $.each(data, function (i, city) {
                    items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
                });
                $('#city').html(items);
            });
        });
    });
    </script>

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

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

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

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

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

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

            <div class="form-group">
                @Html.LabelFor(model => model.CityId, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("City", new SelectList(string.Empty, "Value", "Text"), htmlAttributes: new { id = "city", @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.CityId, "", 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>
</body>
</html>

donator create view:

image of donator create view

after save donator info(index view) image of after save donator info(index view


回答1:


In your POST create controller action, you are not binding CityId. You're binding CountryId, is that a typo?

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,gender,Age,BloodType,CountryId,StateId,CityId")] Donator donator)
{
   // add cityId to the bind parameters above
   ...
}

You'll need to update City to CityId on your html helper.

// please update first string parameter to CityId
@Html.DropDownList("CityId", new SelectList(string.Empty, "Value", "Text"), htmlAttributes: new { id = "city", @class = "form-control" })


来源:https://stackoverflow.com/questions/61212504/dropdown-list-with-ajax-generated-options-not-saving-for-cityid-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!