0

我创建了自己的扩展程序:

public static MvcHtmlString hSearch(this HtmlHelper helper, string labelName, string labelCaption, string textName, string textValue, string tableName, string buttonId, 
        string actionName, string controllerName, object routeValues, object htmlAttributes)
    {            
        var textbuilder = new TagBuilder("input");
        textbuilder.MergeAttribute("id", textName);
        textbuilder.MergeAttribute("name", textName);
        textbuilder.MergeAttribute("value", textValue);
        textbuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));


        ModelMetadata metadata = ModelMetadata.FromStringExpression(labelName, helper.ViewData);
        String innerText = labelCaption ?? (metadata.DisplayName ?? (metadata.PropertyName ?? labelName.Split('.').Last())); 
        if (String.IsNullOrEmpty(innerText)) 
        { 
            return MvcHtmlString.Empty; 
        }
        TagBuilder labelbuilder = new TagBuilder("label");
        labelbuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(labelName)));
        labelbuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        labelbuilder.SetInnerText(innerText);            

        //return new MvcHtmlString(textbuilder.ToString());
        var buttonBuilder = new TagBuilder("button");
        buttonBuilder.MergeAttribute("id", buttonId);
        buttonBuilder.SetInnerText(buttonId);

        var formBuilder = new TagBuilder("form");
        var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);

        formBuilder.Attributes.Add("action", urlHelper.Action(actionName, controllerName, routeValues));

        formBuilder.Attributes.Add("method", "Post");

        formBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

        formBuilder.InnerHtml = labelbuilder.ToString() + textbuilder.ToString() + buttonBuilder.ToString();
        return new MvcHtmlString(formBuilder.ToString());
    }

我在视图中使用了扩展:

 @Html.hSearch("lblSrch", "Company", "companyName", (string)TempData["cName"], "CHComp", "Search", "Fetch", "Home", null, null)

现在我想在单击按钮时将 tableName 传递给控制器​​。我的控制器如下所示:

    public ActionResult Fetch(string search, string tablename)
    {
        var c = cbo.fetchData(search, tablename);
        return PartialView(c.ToList());
    }

等待回复。。谢谢。。

4

1 回答 1

1

您没有向我们提供您的助手的代码,但猜测它会写出一个标签、一个文本字段 (textName) 和一个按钮。如果是这种情况,它将companyName=someValue通过 HTTP 发布/获取回您的控制器。

FormCollection如果字段是从视图动态发送的,您通常需要将 a 添加到控制器中。或者,为什么不将文本搜索输入的名称保持为静态,例如name="search",它将绑定到控制器的同名参数。

编辑 您可以将 tableName 传递回隐藏字段(<input type='hidden' name='tableName' value='{tableNameGoesHere}')中的控制器

但如上所述,您的搜索字符串将具有不同的名称 - 模型绑定器不会将其识别为string search.

于 2012-08-14T04:40:21.177 回答