Mvc4在一个视图中有2个表单

时间:2013-05-02 21:10:16

标签: asp.net-mvc-4

所以我正在构建一个简单的mvc4应用程序,我创建了所有用于创建数据库的基础模型,从这些类中我可以自然地创建具有匹配视图的基本控制器。

现在我的问题:我有基本的create actionresult + view,在这个视图中,我希望用户可以从下拉列表中选择一些值,这样可以简化新对象的创建。

我试图在我的视图中使用第二种形式(第一种是基本的创建形式)来实现这一点,如果我想使用这些下拉列表(它们相互过滤(所以首先用户必须指定一个大陆,然后是下拉列表)国家/地区仅显示来自该大陆的国家/地区,并且在指定国家/地区后,区域下拉列表会更新:)))始终会自动调用基本视图的提交。

所以让下拉列表自行更新不是问题:这是创建的表单在下拉列表更新时自动验证

这是下拉列表相互过滤的控制器

//
// GET: /FederationCenter/Create
public ActionResult Create(string searchRegion, string searchCountry, string searchContinent)
{
  var countries = from c in db.Countries select c;
  if (!String.IsNullOrEmpty(searchContinent))
  {
    Continent searchContinentEnumValue = (Continent)Enum.Parse(typeof(Continent), searchContinent);
    countries = from c in db.Countries where ((int)c.Continent).Equals((int)searchContinentEnumValue) select c;
  }

  var regions = from r in db.Regions where r.Country.Name.Equals(searchCountry) select r;

  ViewBag.searchContinent = new SelectList(Enum.GetNames(typeof(SchoolCup.Domain.Continent)));
  ViewBag.searchCountry = new SelectList(countries, "Name", "Name");
  ViewBag.searchRegion = new SelectList(regions, "Name", "Name");
  return View();
}

//
// POST: /FederationCenter/Create

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(NSSF nssf, string searchRegion, string searchCountry, string searchContinent)
{
  var countries = from c in db.Countries select c;
  if (!String.IsNullOrEmpty(searchContinent))
  {
    Continent searchContinentEnumValue = (Continent)Enum.Parse(typeof(Continent), searchContinent);
    countries = from c in db.Countries where ((int)c.Continent).Equals((int)searchContinentEnumValue) select c;
  }

  var regions = from r in db.Regions where r.Country.Name.Equals(searchCountry) select r;

  ViewBag.searchContinent = new SelectList(Enum.GetNames(typeof(SchoolCup.Domain.Continent)));
  ViewBag.searchCountry = new SelectList(countries, "Name", "Name");
  ViewBag.searchRegion = new SelectList(regions, "Name", "Name");
  if (ModelState.IsValid)
  {
    var naam = Request["searchRegion"];
    Region creatie = (from c in db.Regions where c.Name.Equals(naam) select c).SingleOrDefault();
    nssf.ISFId = 1;
    nssf.RegionId = creatie.RegionId;
    db.NSSFs.Add(nssf);
    db.SaveChanges();
    return RedirectToAction("Index");
  }
  return View(nssf);
}

这是我的观点

@model SchoolCup.Domain.POCO.NSSF

@{
ViewBag.Title = "Create";
}

<h2>Create NSSF</h2>
     <div>
        @using (Html.BeginForm(null, null, FormMethod.Post, new { name = "form" }))
        {
         @Html.AntiForgeryToken()

        @Html.DropDownList("searchContinent", null, "-- All continents --", new { onchange = "sendForm()" }) 
        @Html.DropDownList("searchCountry", null, "-- All countries --", new { onchange = "sendForm()" })
        @Html.DropDownList("searchRegion", null, "-- All regions --", new { onchange = "sendForm()" })
            <>
            <input type="submit" name= value="Search" />    
        }
    </div>   
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    <legend>NSSF</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>

更多输入

   </fieldset>
    <p>
        <input type="submit" value="Create" />
        @Html.ActionLink("Back to List", "Index", null, new { @class = "button" })

    </p>
}

@section Scripts {
<script type="text/javascript">
    function sendForm() {
        document.form.submit()
    }
    </script>
}

我一直在寻找至少一天,我不知道如何解决这个问题

问候 亚历山大

1 个答案:

答案 0 :(得分:2)

如何(1)使用JQuery并使用控制器返回的部分视图加载下拉列表或(2)您可以进行AJAX调用,将您的值作为从您的实体和您映射的JSON对象返回可以在下拉列表中呈现它们。这样,每次更新下拉列表时都不会提交表单。

第一个解决方案可能如下所示:

<强> JQUERY

<script>
$("#searchContinent").change(function() { 
    $("#searchCountry").load("/YourController/GetCountries", { 'continentId': $(this).val() },
                                        function (response, status, xhr) {
                                            if (status == "error") {
                                                alert("An error occurred while loading the results.");
                                            }
                                        });
});
</script>

@Html.DropDownList("searchContinent", null, "-- All continents --" }) 
<div id="searchCountry">
    <!--the newly created drop-down will be placed here-->
</div>

(适用EDIT)

对于Javascript,你可以尝试这样的事情:

您目前的观点

@Html.DropDownList("searchContinent", null, "-- All continents --", new { onchange = "getCountries(this)" }) 
<div id="searchCountry">
<!--the newly created drop-down will be placed here-->
</div>

<script> 
function getCountries(input){
    var selectedValue = input.options[input.selectedIndex].value;
    var xhReq = new XMLHttpRequest();
    xhReq.open("GET", "YourController/GetCountries?continentId="+selectedValue, false);
    xhReq.send(null);
    var serverResponse = xhReq.responseText;
    document.getElementById("searchCountry").innerHTML=serverResponse ;
}
</script>

免责声明:我从未尝试过,如果有错,请不要犹豫,让我知道并在必要时予以纠正

(结束编辑)


<强> CONTROLLER

public ActionResult GetCountries(string continentId)
    {
        /*Get your countries with your continentId and return a Partial View with a list of 
          countries as your model*/


        return PartialView(countryList);
    }

GetCountries VIEW

@model IEnumerable<SchoolCup.Domain.Country>

@Html.DropDownListFor( 0, Model)