【问题标题】:Drop down initiated when click on enter on validated text box单击已验证文本框上的输入时启动下拉菜单
【发布时间】:2014-05-19 14:15:37
【问题描述】:

我创建了一个 MVC5 应用程序,它是由我的模型通过脚手架视图和控制器生成的, 在模型中,我有一个用于 dev 和 prod 的下拉菜单,它工作正常,我有验证 对于字母数字的名称,问题是例如用户选择产品(第二个 选项)并在名称字段中输入不正确的数据并按回车键,视图被刷新并 下拉菜单将选择从 prod 更改为 dev。我怎样才能避免这种情况?

如何在视图中询问类型是否与dev不同,如果是则放置所选项目?

型号:

public class Ad
{
    public int ID { get; set; }

    [RegularExpression(@"^[a-zA-Z0-9]*$", ErrorMessage = "Invalid Name")]
    public string Name { get; set; }

    public IEnumerable<SelectListItem> Type
    {
        get
        {
            return new[]
            {
                new SelectListItem {Value = "D", Text = "Dev"},
                new SelectListItem {Value = "p", Text = "Prod"}
            };
        }
   }

查看:

   <div class="form-group">
        @Html.LabelFor(model => model.SystemType, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
           @Html.DropDownListFor(model => model.Type, Model.Type)
        </div>
    </div>

编辑创建操作

@model WebApplication3.Models.Ad

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
        $(document).ready(function () {
            debugger;

            $('select[name="Type"]').change(function () {
                if ($(this).val() === 'p') {
                    $('input[name="User"]').prop("disabled", true);
                    $('input[name="Password"]').prop("disabled", true);
                }
                else {
                    $('input[name="User"]').prop("disabled", false);
                    $('input[name="Password"]').prop("disabled", false);
                }
            });
        });
    </script>

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

    <div class="form-horizontal">
        <h4>Ad</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Type, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.Type, Model.Type)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.User, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.User)
                @Html.ValidationMessageFor(model => model.User)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Password, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password)
                @Html.ValidationMessageFor(model => model.Password)
            </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")
}

 public class AdController : Controller
 {
        private AdDBContext db = new AdDBContext();

        public ActionResult Index()
        {
            return View(db.Ad.ToList());
        }

        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Ad ad = db.Ad.Find(id);
            if (ad == null)
            {
                return HttpNotFound();
            }
            return View(ad);
        }

        public ActionResult Create()
        {
            return View( new Ad());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="ID,Name,User,Password")] Ad ad)
        {
            if (ModelState.IsValid)
            {
                db.Ad.Add(ad);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(ad);
        }

        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Ad ad = db.Ad.Find(id);
            if (ad == null)
            {
                return HttpNotFound();
            }
            return View(ad);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="ID,Name,User,Password")] Ad ad)
        {
            if (ModelState.IsValid)
            {
                db.Entry(ad).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(ad);
        }

        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Ad ad = db.Ad.Find(id);
            if (ad == null)
            {
                return HttpNotFound();
            }
            return View(ad);
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Ad ad = db.Ad.Find(id);
            db.Ad.Remove(ad);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

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

【问题讨论】:

    标签: c# javascript razor drop-down-menu asp.net-mvc-5


    【解决方案1】:

    在下拉更改事件中将选定的选项值写入隐藏字段,当页面刷新时从隐藏字段中获取值并从操作中设置选定项。

    $('select#Type').change(function(){
    
    $('#selectedOne').val($(this).val());
    
    });
    

    并在您的操作中从 FormCollection 中读取并设置 SelectList 的选定项

    在视图中创建隐藏字段:

    <div class="form-group">
            @Html.LabelFor(model => model.SystemType, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
               @Html.DropDownListFor(model => model.Type, Model.Type)
              <input type="hidden" id="selectedOne" vlaue="" name="selectedOne" />
            </div>
        </div>
    

    在你的行动中:

    [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Create([Bind(Include="ID,Name,User,Password")] Ad ad,FormCollection form)
            {
                string selectedValue = form["selectedOne"].ToString();
                if (ModelState.IsValid)
                {
                    db.Ad.Add(ad);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
    
                foreach(var item in ad.Type)
                {
                  if(item.Value == selectedValue)
                  {
                     item.Selected = true;
                  }
                }
    
                return View(ad);
            }
    

    解决方案 2:

    另一个简单的解决方案是使用@Ajax.BeginForm Hepler 而不是@Html.BeginForm,这样通过ajax 发布的表单就不会被重置。

    【讨论】:

    • HI Ehsan - 非常感谢您快速重播,我是这个主题的新手,请您在我发布的内容中添加代码。提前致谢,我投了赞成票!
    • 您将表单发布到某个操作权,同时发布该操作代码
    • 同时发布您的获取和发布操作
    • 非常感谢!目前它不起作用,当我调试它时,字符串 selectedValue = form["selectedOne"];返回“”,有什么想法吗?我不确定它是如何解决问题的,因为您在哪里将列表框选定项的值传递给视图?
    • 你写过下拉的jquery事件吗
    猜你喜欢
    • 2013-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    相关资源
    最近更新 更多