MVC4 Ajax.BeginForm routeValues converted to Type Name in HTML - asp.net-mvc-4

I'm using Ajax.BeginForm in a MVC 4 Razor View.
#model EditViewDefinition
#{
RouteValueDictionary postParams = new RouteValueDictionary();
postParams.Add("entityUid", Model.EntityUid);
postParams.Add("entityId", ViewBag.entityId);
postParams.Add("viewUid", Model.UID);
string viewContainerId = "viewcontent_" + Model.UID.ToString().ToLower() + "_" + ViewBag.entityId.ToString();
}
then
using (Ajax.BeginForm("Edit", postParams, new AjaxOptions() { HttpMethod = "Post", OnSuccess = "submitSuccess('" + viewContainerId + "')" }))
{
...
}
Now when I check the resulting HTML in the browser, I get:
<form id="form0"
action="/View/Edit?Count=3&Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D"
method="post"
data-ajax-success="submitSuccess('viewcontent_fb1a8d4c-fd30-4da4-b11c-bff99f3bb74f_1')"
data-ajax-method="Post"
data-ajax="true">
...
</form>
Why am I getting System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object in the action attribute instead of action="/View/Edit?entityUid=uid&entityId=1&viewUid=uid?

Thanks to Stephen Muecke's comment. I used var postParams = new { entityUid = Model.EntityUid, entityId = ViewBag.entityId, viewUid = Model.UID }; which worked.
Many Thanks Stephen.

Related

Can you pretty print IHtmlContent?

If I have a IHtmlContent can I pretty print it?
Example:
var html = new HtmlString("<article><h2>Hello!</h2></article>");
I want it pretty printed with line breaks and indention into:
<article>
<h2>Hello!</h2>
</article>
I do not want:
<article><h2>Hello!</h2></article>
You could try to JavaScript to add the line breaks and indention into, then, use <pre> tag to render the html content. Please check the following sample:
Index.cshtml:
#{
var html ="<article><h2>Hello!</h2></article>";
}
<div id="printdiv">
#Html.Raw(html)
</div>
<div id="output">
</div>
<input type='button' id='btn' value='Print' onclick='printDiv();'>
#section Scripts{
<script>
function printDiv() {
var divToPrint = document.getElementById('printdiv');
//display the pretty html content in the web page.
document.getElementById("output").innerHTML = "<pre>" + process(divToPrint.innerHTML).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") + "</pre>";
//create a new window to print the div content.
var newWin = window.open('', 'Print-Window');
newWin.document.open();
newWin.document.write('<html><body onload="window.print()"><pre>' + process(divToPrint.innerHTML).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") + '</pre></body></html>');
newWin.document.close();
setTimeout(function () { newWin.close(); }, 10);
}
function process(str) {
var div = document.createElement('div');
div.innerHTML = str.trim();
return format(div, 0).innerHTML;
}
function format(node, level) {
var indentBefore = new Array(level++ + 1).join(' '),
indentAfter = new Array(level - 1).join(' '),
textNode;
for (var i = 0; i < node.children.length; i++) {
textNode = document.createTextNode('\n' + indentBefore);
node.insertBefore(textNode, node.children[i]);
format(node.children[i], level);
if (node.lastElementChild == node.children[i]) {
textNode = document.createTextNode('\n' + indentAfter);
node.appendChild(textNode);
}
}
return node;
}
</script>
}
The result like this:
You can parse it XML with XDocument.Parse then use XmlWriter with its settings set to Indent to true. Worked for me on my HTML too.
var html = new HtmlString("<article><h2>Hello!</h2></article>");
using var writer = new StringWriter();
html.WriteTo(writer, HtmlEncoder.Default);
var htmlString = writer.ToString();
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Encoding = Encoding.UTF8,
Indent = true,
};
var sb = new StringBuilder();
using (var writer = XmlWriter.Create(sb, settings))
{
XDocument.Parse(htmlString).Save(writer);
}
Console.WriteLine(sb.ToString());

MVC ResultStream only working with link

I'm creating a barcode using ASP.Net MVC
The problem is it's working with links. But it needs to work with form values.
This is my controller :
[HttpPost]
public ActionResult Barcode(BarcodeModel B)
{
string BarcodeTitle = B.BarkodTitle;
string BarcodeNumber = B.BarcodeNumber;
Codec objbar = new Codec();
Byte[] BarcodeImage = objbar.getBarcodeImage(BarcodeNumber, BarcodeTitle);
Stream Memory = new MemoryStream(BarcodeImage);
Memory.Position = 0;
var Result = new FileStreamResult(Memory, "image/png");
Result.FileDownloadName = String.Format("{0}.png", BarcodeTitle);
return Result ;
}
This is my JavaScript code :
<script type="text/javascript">
function BarkodKaydet()
{
var BarkodModel = new Object();
BarkodModel.DeweyCode = document.getElementById('DeweyCode').value;
BarkodModel.CutterNumber = document.getElementById('CutterNumber').value;
BarkodModel.Year = document.getElementById('Year').value;
BarkodModel.Bind = document.getElementById('Bind').value;
BarkodModel.Copy = document.getElementById('Copy').value;
BarkodModel.BarcodeTitle = document.getElementById('BarcodeTitle').value;
BarkodModel.BarcodeNumber = document.getElementById('BarcodeNumber').value;
$.ajax({
type: "post",
url: "#Url.Action("Barcode")",
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(BarkodModel),
success: function (data) { console.log(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
But it's not working.
It' just working with link how I'm changing controller to ;
public ActionResult Barcode(string barcodeNumber, string barcodeText)
{
Codec objbar = new Codec();
Byte[] BarkodImage = objbar.getBarcodeImage(barcodeNumber, barcodeTitle);
Stream Memory = new MemoryStream(BarcodeImage);
Memory.Position = 0;
var Result = new FileStreamResult(Memory, "image/png");
Result.FileDownloadName = String.Format("{0}.png", BarcodeTitle);
return Result ;
}
this and change view to ;
<img src="/Home/BarcodeImage?barcodeText=Can&barcodeNo=12345" />
to this.
When the page opening, the linked image sending values to controller and showing barcode to me.
But I need;
When the form values submitting to model, ActionResult needs to create barcode from model, refresh the same page and It will show only barcodeImage to me.
How can I configure it ?
Best regards.

Controller is not returning Viewbag value to the View

I have a controller named CallAllocation, and a View CallAllocation.
At first when the page loads only two dropdown appears with a submit button. On submission, page gets filled with rest of the details based on the selection from the two dropdowns. To achieve that I have made the following code:
Please focus on ViewBag.IsValid condition
My Controller be like
[HttpGet]
public ActionResult CallAllocation()
{
ViewBag.UserName = User.Identity.Name.ToString();
try
{
var NatureList = (from a in dataContext.CallNatures
select a);
Allocation Allocate = new Allocation();
Allocate.CallNaturelist = NatureList.ToList();
ViewData["SelectedTicket"] = 0;
Allocate.CallTicketList = null;
ViewBag.IsValid = "";
return View(Allocate);
}
catch (Exception ex)
{
TempData["ErrMsg"] = ex.Message;
return RedirectToAction("ShowError");
}
}
My View be like
#using (Html.BeginForm("CallAllocation", "Home", FormMethod.Post, new { id = "FrmCallAllocate"}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
#Html.Raw(ViewBag.ErrMsg)
<div class="row ">
<div class="col-sm-12">
#if (ViewBag.IsVaild == "True")
{
#Html.DropDownListFor(m => m.SelectedCallNature, new SelectList(Model.CallNaturelist, "CallNatureID", "Description"),
"Select Nature", new { style = "width:250px", #class = "dropdown1", #readonly = "readonly;" })
#Html.DropDownList("CallTicket", new SelectList(string.Empty, "CallTicketNumber", "CallTicketNumber"), "Select Call Ticket",
new { style = "width:250px", #class = "dropdown1" , #readonly = "readonly;" })
<input type="submit" value="Get Ticket" style="background-color:#C5C5C5"/>
}
else
{
#Html.DropDownListFor(m => m.SelectedCallNature, new SelectList(Model.CallNaturelist, "CallNatureID", "Description"),
"Select Nature", new { style = "width:250px", #class = "dropdown1" })
#Html.DropDownList("CallTicket", new SelectList(string.Empty, "CallTicketNumber", "CallTicketNumber"), "Select Call Ticket",
new { style = "width:250px", #class = "dropdown1"})
<input type="submit" value="Get Ticket" style="background-color:#C5C5C5"/>
}
</div>
</div>
}
As you can see Controller sends ViewBag value "", and it should enter else condition of the View. But it is bypassing both the conditions.
Please help me understand why the controller is unable to send Viewbag value to the view. I have made similar cases but it's working in rest.
I have tried clearing the cache too.
Please note that my View is a strongly-typed View.

formData.append() not working - checked in Chrome,Mozilla, IE

Am using Jquery FormData for the first time, but seems am missing something. In the JS - postAjax method, when new FormData() is called, it just skips the remaining lines and goes to the end of the function without any errors. What am I doing wrong here?
template.js //script files in this order
<script src="js/jquery-2.1.0.js"></script>
<script src="js/jquery.form.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrapValidator.js"></script>
<script src="js/hemoncCBCFunctions.js"></script>
<script src="js/validations.js"></script>
JSP
<form name ="newSectionSubmitForm" id="newSectionSubmitForm" class="form-horizontal" role="form" method="post" ENCTYPE="multipart/form-data">
<table>
<tr>
<td>
<input type="file" id='imageFile0' name='imageFile0' class="form-control" />
</td>
</tr>
</table>
<form>
JS
function submitNewSection(targetUrl, form) {
postAjaxData(null, 'content', targetUrl, form, null, null);
}
function postAjaxData(initiatingElement, targetElement, targetUrl, form,
additionalParamMap, successCallback) {
var $targetElement = $('#' + targetElement);
var serializedFormData;
serializedFormData = $('#' + form).serialize();
for ( var j in additionalParamMap) {
serializedFormData += "&" + j + "=" + additionalParamMap[j];
}
alert('serialized form data ' + serializedFormData);
var formData = new FormData(serializedFormData);//**exits the function no errors**
formData.append("file", $('#imageFile0').files[0]);
alert('serialized form data ' + formData);
$.ajax({
type : "POST",
cache : false,
data : formData,
url : targetUrl,
success : function(data) {
processRedirect(data);
$targetElement.html(data);
$targetElement.show();
if (successCallback != null) {
successCallback(data);
}
},
error : function(xhr, httpRequest, textStatus, errorThrown) {
var errorId = xhr.getResponseHeader("errorId");
var errorMsg = xhr.getResponseHeader("errorMessage");
if (errorId != null && errorId != undefined) {
$("#page_error").html(
"An unexpected error has occurred. Error Id: "
+ errorId);
} else {
$("#page_error").html("An unexpected error has occurred.");
}
},
});
Controller File (however the code does not reach here)
#RequestMapping(value = "/submitNewSection.html")
public String submitNewSection( MultipartHttpServletRequest req, HttpServletRequest request, Model model) {
Iterator<String> itr = req.getFileNames();
MultipartFile mpf = req.getFile(itr.next());
System.out.println("file name " + mpf.getOriginalFilename() +" uploaded!");
}
Thanks so much.

How to export MVC webgrid results to pdf and excel directly without using any third party control?(iTEXtSharp i not working)

I have tried itextsharp samples and the serializing to xml .
Am using Entity frame work 6.0
and asp.net mvc4
I'm using following for export to excel:
In your Controller:
public ActionResult ExportData()
{
var datasource = db.Products.ToList();
GridView gv = new GridView();
gv.DataSource = datasource;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return Json("Success");
}
In View:
#using (Html.BeginForm("ExportData", "Home", FormMethod.Post))
{
<button type="Submit">Export to Excel</button>
}
//OR:
#Html.ActionLink("Export to Excel", "ExportData", "Home")
As to export to PDF, I'd recommend to use Rotativa. Works ok for me.
EDITED
I'm using filters too. You may send it's value from View to controller action and modify datasource. For example:
public ActionResult ExportData(DateTime fromDate)
{
var datasource = db.Products.Where(g=>g.Date <= fromDate).ToList();
Try this:
var data = GetFeedbackDetailsExport();
var gridWeb = new WebGrid(source: data, canPage: false, canSort: false);
string exportData = gridWeb.GetHtml(
columns: gridWeb.Columns(
gridWeb.Column("EnterpriseId", "EnterpriseId"),
gridWeb.Column("GroupName", "Group Name"),
gridWeb.Column("Geography", "Geography"),
gridWeb.Column("Country", "Country"),
gridWeb.Column("DeliveryCentre", "Delivery Centre"),
gridWeb.Column("Vendor", "Vendor Name"),
gridWeb.Column("Category", "Category"),
gridWeb.Column("ModelName", "ModelName"),
gridWeb.Column("Status", "Status"),
gridWeb.Column("Date_Submitted", "Submitted On", format: (item) => item.Date_Submitted != null ? item.Date_Submitted.ToString("dd/MMM/yyyy") : ""),
gridWeb.Column("UpdatedBy", "Feedback Given By", style: "col-lg-1"),
gridWeb.Column("UpdatedOn", "Feedback Given On", format: (item) => item.UpdatedOn != null ? item.UpdatedOn.ToString("dd/MMM/yyyy") : "")
)
).ToHtmlString();
return File(new System.Text.UTF8Encoding().GetBytes(exportData),
"application/vnd.ms-excel",
"FeedbackReport.xls");