我正在尝试将生成的HTML字符串返回到视图,以动态生成包含结果的HTML表。我无法获得返回的HTML字符串任何建议和帮助非常感谢。
这是我的控制器代码
public ActionResult ValidateTrams()
{
string html = "";
if (Request.Files.Count == 0 || Request.Files[0].ContentLength == 0)
{
}
else
{
html = ProcessTextFile(Request.Files[0].InputStream);
}
return View(html);
}
我正试图像这样
在jquery中获取这个返回的结果$('#tramsView').live('click', function () {
$.ajax({
url: '/Booking/ValidateTrams',
type: 'POST',
dataType: 'jsonp',
success: function (data) {
alert(data);
$('#TramsViewFrame').html(data);
},
error: function (jqxhr, textStatus, errorThrown) {
$(window).hideWaitScreen();
if (confirm(errorThrown)) { window.location.reload(); }
}
});
});
最后,下面是表单的CSHTML。在这里,我正在从一个带有按钮类型提交
的表单中读取文件<form action="#" method="post" enctype="multipart/form-data" class="forms" name="form"
id="frmvalidate">
<table>
<tr>
<td>
<input type='file' name='trams' id='ValidatetramsFile' />
</td>
</tr>
<tr>
<td>
<br />
<input name="cbDisplayUmatched" id="cbDisplayUmatched" type="checkbox" value="" checked="true" />
<label style="text-decoration: none; outline: none; font-size: 1.1em; padding: 3px 0 0px 0;">
Display rows that were <strong>NOT</strong> parsed</label>
</td>
</tr>
<tr>
<td>
<br />
<div class="buttons">
<button type="submit" value="VIEW" class="ui-state-default ui-corner-all" id="tramsView">VIEW</button>
</div>
</td>
</tr>
</table>
</form>
感谢您的时间,非常感谢您的帮助。亲切的问候!!!
答案 0 :(得分:14)
你可以从这样的行动中返回HTML,
return Content(html, "text/xml");
答案 1 :(得分:4)
听起来好像你的表单仍在提交正常的回发,所以你正在做的任何异步调用都会丢失。
尝试使用以下内容阻止提交默认表单:
$('#tramsView').live('click', function (evt) {
evt.preventDefault();
// ... rest of your code
});
顺便提一下,在这种情况下,如果你正在做的就是更新#TramsViewFrame
上的html,你可以使用稍微简单的$.load()方法:
$('#tramsView').live('click', function (evt) {
evt.preventDefault();
$('#TramsViewFrame').load('/Booking/ValidateTrams');
});
答案 2 :(得分:3)
进行这些更改
将属性HttpPost置于控制器之上
[HttpPost]
public ActionResult ValidateTrams()
从控制器返回像Json一样的字符串。
return Json(new { success = html });
最后将您的数据类型从 更改为jsonp
json
$('#tramsView').live('click', function() {
$.ajax({
url: '/Booking/ValidateTrams',
type: 'POST',
dataType: 'json',
success: function(data) {
alert(data.success);
$('#TramsViewFrame').html(data.success);
},
error: function(jqxhr, textStatus, errorThrown) {
$(window).hideWaitScreen();
if (confirm(errorThrown)) {
window.location.reload();
}
}
});
});
P.S:如果您使用的是最新版本的jQuery(1.7 +),请将.live
处理程序更改为.on
处理程序。不是强制性的:)
答案 3 :(得分:1)
在您的控制器中,因为您使用的是ajax帖子,您需要以JSON身份返回它会是这样的
return Json(html);
答案 4 :(得分:0)
我认为这是与您的方案相关的另一种方式How can I return the HTML from MVC controller to a div in my view
http://mazharkaunain.blogspot.com/2011/02/how-to-use-aspnet-mvc-javascriptresult.html
答案 5 :(得分:0)
而不是存储在&#34;字符串&#34;以下列格式存储HTML代码:
HtmlString s = new HtmlString("<html coding/>");
ViewData["Id_as_per_your_choice"] = s;
return View("page_you_want to_respond");
然后放置&#34;&lt;%:ViewData [&#34; Id_Same_as_that_in_above_code&#34;]%&gt;&#34;哪里有你想要的HTML代码出现......简单..... 但是在&#34; index()&#34;方法中将Viewdata的初始值设为null,以便代码不会出现在页面加载中....