简体   繁体   English

将大型HTML字符串从View传递给Controller

[英]Passing a large HTML string from View to Controller

Note: I'm a front-end developer wearing a .Net developer's hat for now. 注意:我现在是戴着.Net开发人员的前端开发人员。 Laughable, I know, but how I ended up in this mess is not the point of this question. 可笑,我知道,但是我最终陷入这个混乱局面并不是这个问题的重点。 With that disclaimer out of the way, here's what is happening. 有了免责声明,这就是正在发生的事情。

As the title suggests, I need to pass a quite long HTML string (as in multiple pages of text) from a View to a Controller. 正如标题所示,我需要将一个相当长的HTML字符串(如在多页文本中)从View传递给Controller。 I spent the last few days researching various ways to achieve this. 我花了最后几天研究各种方法来实现这一目标。 TBH, some things made sense while some didn't. TBH,有些事情是有道理的,有些则没有。

Here's my code piece inside View : 这是我的代码片段里面的视图

var html =
    "<form id='htmlContent' action='" + customUrl + "' method='post'>" +
        "<input type='hidden' name='content' id='contentStr'>" +
    "</form>";

// string literal html gets appended to some element...

$("#htmlContent").submit();

A few things I'd like to point out here: 我想在此指出一些事项:

  • I'm using a string literal to construct the form here because this DOM needs to be dynamically attached to other element at some point. 我在这里使用字符串文字来构造表单,因为这个DOM需要在某个时刻动态地附加到其他元素。
  • Whether I'm using a valid HTML string is out of the question. 我是否使用有效的HTML字符串是不可能的。 I've already tested its validity separately and everything looks fine. 我已经分别测试了它的有效性,一切看起来都很好。
  • I'm intentionally using jQuery's submit() method instead of using Ajax call. 我故意使用jQuery的submit()方法而不是使用Ajax调用。

Controller: 控制器:

[HttpPost]
public ActionResult ParseHtml(FormCollection form)
{
    string htmlStr = form["content"].ToString();
    ....
    // some code in between, but the first line appears to be causing an error or
    // the value is not being retrieved.
    ....
    return new EmptyResult();
}

I understand I'm working within the context of MVC framework and I sort of comprehend the concept of it. 我理解我在MVC框架的上下文中工作,我有点理解它的概念。 But, knowing how to implement it with my very limited knowledge is another thing (especially when you inherited a bad code base from someone who's long gone from your project!) 但是,知道如何用我非常有限的知识来实现​​它是另一回事(特别是当你从一个早已离开你的项目的人那里继承了一个糟糕的代码库时!)

I'd like to think this is quite straightforward and easy to do, but I've been spinning my wheels for much longer than I'd like to. 我想这很简单易行,但我的轮子旋转时间比我想要的长得多。 Any pointers to the right direction will be much appreciated. 任何指向正确方向的指针都将非常感激。

In this minimal reproducible answer, I'll show you how to get this working, and you can run with it from here: 在这个可重复性最小的答案中,我将向您展示如何使其工作,您可以从这里运行它:

Index.cshtml Index.cshtml

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var url = '@Url.Action("Create","Stack")';
        var html = $("<form id='htmlContent' action='"+url+"' method='post'><input type='hidden' name='content' id='contentStr' value='oranges'/></form>");
        $(body).append(html);

        $("#htmlContent").submit();
    });
</script>

@{
    ViewBag.Title = "title";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>title</h2>

Controller.cs Controller.cs

using System.Web.Mvc;

namespace MvcPlayground.Controllers
{
    public class StackController : Controller
    {
        //
        // GET: /Stack/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create(FormCollection form)
        {
            string htmlStr = form["content"].ToString();

            return View("Index");
        }
    }
}

If you place a breakpoint on the return View("Index"); 如果在return View("Index");上放置断点return View("Index"); , you'll see htmlStr is "oranges", which is the value of the appended textbox. ,你会看到htmlStr是“oranges”,这是附加文本框的值。

Not answering the main part of your question as I'm not certain of all of the details, sorry. 不回答问题的主要部分,因为我不确定所有细节,抱歉。 I'm not saying you're doing it "wrong" by any stretch as I'm not certain what peripherally may make it seem like it is necessary, but you may be creating a situation where you're going to have a major headache on the backend parsing and what not. 我并不是说你在任何方面做错都是“错误的”因为我不确定外围可能会让它看起来像是必要的,但你可能会创造一种你将会头疼的局面在后端解析和什么不解析。 Good chance that a lot of this is all wrong as I'm not certain of the requirements so I apologize. 由于我不确定这些要求所以很有可能这很多都是错的,所以我道歉。

"I'm using a string literal to construct the form here because this 
 DOM needs to be dynamically attached to other element at some point."

You're wanting to re-render that same element in another component? 您想要在另一个组件中重新渲染相同的元素吗? That sounds like you're looking for a partial view. 这听起来像是在寻找局部视图。 With that, you can render it in View1 and use it in View2 with the same data. 有了它,您可以在View1中渲染它并在View2中使用相同的数据。 If you're trying to create elements on the fly, I imagine you're using some type of pattern (ie there's a project I'm working on where I iterate over a collection and do 如果你正在尝试动态创建元素,我想你正在使用某种类型的模式(即我正在研究一个项目,我在那里迭代一个集合并做

<input type='text' id='attribute_@(item.Id)' name='attribute_@(item.Id)' />

And then iterate over the FormCollections AllKeys element to get them (parsing out the attribute_ and what have you like: 然后遍历FormCollections AllKeys元素来获取它们(解析出attribute_以及你喜欢什么:

foreach(var key in form.AllKeys)
{
  var id = Convert.ToInt32(key.Replace("attribute_", "")); // may want to TryParse
  var item = Item.GetItemById(id);
  item.Value = form[key];
  item.Update();
}

Somewhere in the view, you're using javascript to set document.getElementById("contentStr") (not sure if intentional, but your id and name are different. Not a bad thing per se, but could lead to an oops)? 在视图的某个地方,你使用javascript来设置document.getElementById(“contentStr”)(不确定是否有意,但你的id和名称是不同的。本身不是坏事,但可能导致oops)? Then again, not sure what var html = is being used for here. 然后再次,不确定var html =在这里使用了什么。 Razor views you could just do the regular html of [form] ... [/form]. Razor认为你可以只做[form] ... [/ form]的常规html。 Are you doing something like this prior to the submit action? 你是否在提交行动之前做了类似的事情?

$('#content').val(html);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM