0

我想在 mvc4 razor 视图中返回 httpget 上的空模型。一旦用户从下拉列表中选择值,我将在 httppost 上获取模型。这就是我所拥有的:

 [HttpGet]
        public ActionResult AddNewAgent()
        {                   
            var modelAgentt = _fe.Agents.Take(1);           
            SelectList sl = new SelectList((from s in _aa.Agent.ToList() select new {COUNTER = s.COUNTER, FullName = s.LASTNAME + ", " + s.FIRSTNAME}), "COUNTER", "FullName", null);
            ViewBag.Agent= sl;
            return View(agg);
        }

然后在 HttpPost 我有:

[HttpPost]
        public ActionResult AddNewAgent(int? LamcomAgents)
        {    
            var modelAgent = _fe.Agents.Take(10);
            SelectList sl = new SelectList((from s in _aa.Agent.ToList() select new { COUNTER = s.COUNTER, FullName = s.LASTNAME + ", " + s.FIRSTNAME }), "COUNTER", "FullName", null);
            ViewBag.Agent= sl;
            if (LamcomAgents != null && LamcomAgents != 0)
            {
                return View(modelAgent);                
            }
            return View(modelAgent);            
        }

正确的 linq 查询仍未包含在 httppost 操作中,但我稍后会这样做,我只想知道如何在第一次运行时为 httpget 传递可空模型而不会在视图中出现错误。这就是我的观点:

@model IEnumerable<Company.Agents>

@{
    ViewBag.Title = "AddNewAgent";
}

<h2>Add New Agent</h2>

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

    <fieldset>
        <p>Agents in System @Html.DropDownList("Agent", String.Empty)&nbsp;&nbsp; <input type="submit" name="Get Agent" value="Get Agent" title="Get Agent" id="btnGetAgent" /></p>
        <legend>Agents</legend>      
   <table>       
                    <tr>
                        <th>@Html.DisplayNameFor(model => model.A_FirstName)</th>
                        <th></th>
                    </tr>
                    <tr>

                    </tr>              
            @foreach(var item in Model)
            {
                <tr><td>
               @Html.DisplayFor(modelItem => item.A_FirstName)
                    </td></tr>
            }
                </table>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

提前致谢, Laziale

4

1 回答 1

1

假设modelAgentt是类型IEnumerable<Company.Agents>

我认为您需要通过modelAgentt查看而不是agg

因此,从 Get Method 中更改您的代码

return View(agg);

return View(modelAgentt);
于 2013-09-30T12:37:41.603 回答