mvc4 razor在httpget上返回空模型

时间:2013-09-30 11:46:13

标签: asp.net-mvc linq asp.net-mvc-4 razor model

我想在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

1 个答案:

答案 0 :(得分:1)

假设modelAgentt的类型为IEnumerable<Company.Agents>

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

所以在Get Method

中更改代码
return View(agg);

return View(modelAgentt);