MVC3 ajax更新强类型局部视图中的字段

时间:2012-11-21 09:21:04

标签: asp.net-mvc asp.net-mvc-3 razor


我在使用MVC3时遇到了一些麻烦。 我有一个强类型的局部视图包含一个表单。它嵌入在一个大页面中。我想将此部分视图提交给控制器并更新一些字段。在更新之后,我希望嵌入在页面中的部分视图被替换为html包含新值,因为声明了UpdateTargetId,但事实并非如此。不知道我是否能做到这一点。任何帮助将不胜感激。
代码为:

public ActionResult Employee(Employee em)
{
    var em1 = new Employee
    {
        Id = 1,
        Name = "xing yanguang",
        Code = "131324e12"
    };

    return PartialView(em);
}

局部视图中的代码:

employee partial view

1 个答案:

答案 0 :(得分:0)

试试这个 修改部分视图

//In Partial View 

 @model MvcApplication1.Employee

    <table>
        <tr>
            <td>
                @Html.TextBoxFor(m => m.Id)
            </td>
            <td>
                @Html.TextBoxFor(m => m.Name)
            </td>
             <td>
                @Html.TextBoxFor(m => m.Code)
            </td>
        </tr>
    </table>  

Now in your parent view 



// In View.cshtml
    <div id="div_employee">
       @Partail("partailView",Model)
    </div>
       @using (Ajax.BeginForm("Employee", "PO", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "div_employee", InsertionMode = InsertionMode.Replace }))
       {
           <input type="submit" value="save" />
       }

在控制器

public string Employee(Employee em)
{
    var em1 = new Employee
    {
        Id = 1,
        Name = "xing yanguang",
        Code = "131324e12"
    };

    return RenderPartialViewToString("partailView",em1);
}


protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }  

在控制器中添加一个方法来获取部分视图的RenderHtml,通过将 PartailViewName 模型传递给RenderPartialViewToString方法,它将返回具有更新值的视图的Htmlstring。