Jquery form post Issues - asp.net-mvc

I am using asp.net MVC and I am having an issue posting a form using jquery.
It is not posting to the url I am telling it to.
If I use firebug, it shows the post happening but it is posting to the index of the controller everytime. I cannot figure out why. I have verified the url of the action I am trying to post but I can't figure out why it is always posting to the index of the controller....Note: the view in which the form is found IS the index view. so Basically it is posting to it's own action rather than the one in the url i am telling it to. Any help would be great. thanks!
here is my form
<form action='' id="descriptionForm">
<%=Html.Hidden("claimNumber", ViewData["claimNumber"])%>
<%=Html.Hidden("partNumber", ViewData["partNumber"])%>
<%=Html.Hidden("qty", ViewData["qty"])%>
<table>
<tr>
<td style="text-align: right">
Category:
</td>
<td>
<%=Html.DropDownList("problemCategory", (IEnumerable<SelectListItem>)ViewData["problemSelect"], "-Select-")%>
</td>
</tr>
<tr>
<td style="text-align: right">
Details:
</td>
<td>
<select id="problemDetails">
</select>
</td>
</tr>
<tr>
<td style="text-align: right">
Dealer Notes:
</td>
<td>
<%=Html.TextArea("dealerNotes", "", 3, 40, null)%>
</td>
</tr>
</table>
<div style="position: absolute; bottom: 8px; right: 8px">
<input type="button" id="itemDetailsCancel" value="Cancel" />
<input type="submit" id="itemDetailsSubmit" value="Save" />
</div>
</form>
<a href='<%=ResolveUrl("~/Warranty/WarrantyClaims/CompleteAddLineItemToClaim/") %>'
id="CompleteLineItemUrl"></a>
Here is my Javascript
$("#descriptionForm").submit(function () {
var completeurl = $("#CompleteLineItemUrl").attr('href');
var data = $(this).serialize();
$.post({
type:'POST',
url: completeurl,
data: data,
success: function (result) {
alert("done");
}
});
return false
});
and just for good measure here is the controller action I am trying to post to(though it doesn't do much yet)
[HttpPost]
public ActionResult CompleteAddLineItemToClaim(string claimNumber, string partNumber, string qty, string problemCategory, string problemDetails, string dealerNotes)
{
var result = new { result = "done" };
return Json(result, JsonRequestBehavior.AllowGet);
}
Update:
updated javascript
$(function(){
$('#descriptionForm').submit(function () {
var completeurl = $('#CompleteLineItemUrl').attr('href');
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: completeurl,
data: data,
success: function (result) {
alert('done');
}
});
return false;
});
});

Is the form itself loaded by an ajax call?
If so you need to use the live() function of jquery.

Make sure you have wrapped your javascript in a document.ready before subscribing for any events. Also you have a missing ; when returning false at the end of your method.
But your real problem is that you want to use $.ajax instead of $.post. So what actually happens is that you are getting a javascript error because of wrongly using the $.post function and the .submit handler never has time to return false and cancel the default submission of the form and the browser happily proceeds into POSTing to the action of the form (which is empty and default to the action that rendered this form).
So to sum up:
$(function() {
$('#descriptionForm').submit(function () {
var completeurl = $('#CompleteLineItemUrl').attr('href');
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: completeurl,
data: data,
success: function (result) {
alert('done');
}
});
return false;
});
});
Or if you wanted to use $.post:
$(function() {
$('#descriptionForm').submit(function () {
var completeurl = $('#CompleteLineItemUrl').attr('href');
var data = $(this).serialize();
$.post(completeurl, data, function (result) {
alert('done');
});
return false;
});
});
Also instead of generating links à la classic WebForms way:
In ASP.NET MVC you use HTML helpers in order to ensure that link urls are conform to your routes:
<%= Html.ActionLink(
"Link text",
"CompleteAddLineItemToClaim",
"WarrantyClaims",
new { area = "Warranty" },
new { id = "CompleteLineItemUrl" }
) %>

Related

Pass Object Parameter from javascript\ajax to function in Controller

I have a table that i want to be able to update the status of each line that checkbox is on
(see attached screenshot)
The checkbox propery in the Model is Not Mapped to the database ([NotMapped])
Html:
<div class="row">
<div class="col-12 text-right">
<button class="btn btn-primary" onclick="ApproveStatus()">Approve Checked Lines</button>
</div>
</div>
javaScript:
#section Scripts{
<script type="text/javascript">
function ApproveStatus() {
var pdata = new FormData();
swal({
title: "Are you sure?",
text: "Once Updated, you will not be able to Undo this",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
$.ajax({
url: "PaymentHistory/ApproveStatus",
type: "POST",
data: pdata,
processData: false,
contentType: false,
success: function (data) {
swal("Success!", {
icon: "success",
});
}
});
setTimeout(function () {
location.reload()
}, 100);
} else {
swal("Nothing Changed!");
}
});
}
</script>
}
And in the Controller i have the function (haven't written the logic yet)
[HttpPost]
public IActionResult ApproveStatus()
{
}
table in html:
<table id="tblData" class="table table-striped table-bordered" style="width:100%">
<thead class="thead-dark">
<tr class="table-info">
<th>Address</th>
<th>Payment Type</th>
<th>Amount</th>
<th>Payment Date</th>
<th>Status</th>
<th></th>
</thead>
#foreach (PaymentHistory paymentHistory in Model)
{
<tr>
<td>#ViewBag.getPaymentAddress(paymentHistory.SentFromAddressId).ToString()</td> <td>#ViewBag.getPaymentType(paymentHistory.SentFromAddressId).ToString()</td>
<td>#paymentHistory.Amount$</td>
<td>#paymentHistory.PayDate</td>
<td>#paymentHistory.Status</td>
#if (paymentHistory.Status != "Approved")
{
<td>
<div class="text-center">
<input type="checkbox" asp-for="#paymentHistory.isChecked"/>
</div>
</td>
}
else
{
<td></td>
}
</tr>
}
</table>
My only issue is that i want to pass the Object from the View (that contains the lines and status of the checkbox) to the function in the controller as a parameter,
Any ideas how can i do this?
Thank you
i want to pass the Object from the View (that contains the lines and status of the checkbox) to the function in the controller as a parameter, Any ideas how can i do this?
To achieve your requirement, you can try to add a hidden field for SentFromAddressId field, like below.
<td>
<div class="text-center">
<input type="hidden" asp-for="#paymentHistory.SentFromAddressId" />
<input type="checkbox" asp-for="#paymentHistory.isChecked" />
</div>
</td>
then you can get the sentFromAddressId of each checked row and populate it in form data object.
var pdata = new FormData();
$("input[name='paymentHistory.isChecked']:checked").each(function (index, el) {
var sentFromAddressId = $(this).siblings("input[type='hidden']").val();
pdata.append("Ids", sentFromAddressId);
})
and post the data to action method with following code snippet.
$.ajax({
type: 'POST',
url: '/PaymentHistory/ApproveStatus',
data: pdata,
processData: false,
contentType: false,
datatype: 'json',
success: function (res) {
//...
}
});
ApproveStatus action method
public IActionResult ApproveStatus(int[] Ids)
{
//code logic here
//update corresponding record based on id within Ids
Get all checked checkboxes id in an array, use that array to update table

checkbox value always showing null value in mvc

I am always getting null value through checkbox in mvc. If the checkbox is checked or uncheck it contain null value only.
Here is my code,
View Page
#model IEnumerable<SchoolWebApplication.Models.EventMaster>
<table id="tblEvent" class="table" cellpadding="0" cellspacing="0">
<tr>
<th style="width:100px; display:none">Event Id</th>
<th style="width:150px">Event</th>
<th style="width:150px">Active</th>
</tr>
#if(Model != null)
{
foreach (SchoolWebApplication.Models.EventMaster eventMaster in Model)
{
<tr>
<td class="EventID" style="display:none">
<span>#eventMaster.EventID</span>
</td>
<td class="Event">
<span style="color:darkgreen">#eventMaster.Event</span>
<input type="text" value="#eventMaster.Event" style="display:none; color:darkgreen" />
</td>
<td class="IsActive">
<span style="color:darkgreen">#eventMaster.IsActive</span>
#if (#eventMaster.IsActive == true)
{
<input type="checkbox" value="#eventMaster.IsActive" style="display:none; color:darkgreen" checked="checked" name="abc"/>
}
else
{
<input type="checkbox" value="#eventMaster.IsActive" style="display:none; color:darkgreen" name="abc"/>
}
</td>
<td>
<a class="Edit" href="javascript:;">Edit</a>
<a class="Update" href="javascript:;" style="display:none">Update</a>
<a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
</td>
</tr>
}
}
</table>
<script type="text/javascript">
function AppendRow(row, EventID, Event, IsActive) {
//Bind EventID.
$(".EventID", row).find("span").html(EventID);
//Bind Event.
$(".Event", row).find("span").html(Event);
$(".Event", row).find("input").val(Event);
//Bind IsActive.
$(".IsActive", row).find("span").html(IsActive);
$(".IsActive", row).find("input").val(IsActive);
$("#tblEvent").append(row);
};
//Edit event handler.
$("body").on("click", "#tblEvent .Edit", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length >= 0) {
$(this).find("input").show();
$(this).find("span").hide();
}
});
row.find(".Update").show();
row.find(".Cancel").show();
$(this).hide();
});
//Update event handler.
$("body").on("click", "#tblEvent .Update", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length >= 0) {
var span = $(this).find("span");
var input = $(this).find("input");
span.html(input.val());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Cancel").hide();
$(this).hide();
var event = {};
event.EventID = row.find(".EventID").find("span").html();
event.Event = row.find(".Event").find("span").html();
event.IsActive = row.find(".IsActive").find("span").html();
$.ajax({
type: "POST",
url: "/Event/Update",
data: JSON.stringify({ eventMaster: event }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.IsActive);
}
});
});
</script>
Controller
try
{
EventMaster updatedEvent = (from c in entities.eventMaster
where c.EventID == eventMaster.EventID
select c).FirstOrDefault();
updatedEvent.Event = eventMaster.Event;
updatedEvent.IsActive = eventMaster.IsActive;
entities.SaveChanges();
return new EmptyResult();
}
catch (Exception ex)
{
return View();
}
Now, in table there is a three field EventID, Event and Active. In active there is a checkbox containing at update time.
Now, the issue is coming that if the checkbox is check or not check it is containing null value only.
So thats why at the fetch time it showing uncheck only.
Thank You.
Asking for the .val of a checkbox will get you the contents (if any) of the value attribute on the input element - this will not change when the user checks the box.
To check if a checkbox is checked in jQuery you should use something like:
if (input.is(":checked")){}
At the moment, you're storing the current value of .IsActive in the span and the value of the checkbox, and then when the update method runs, just grabbing that same value and putting it into the span - resulting in not updating anything.
Looking further at your code though - you should confirm what your method is actually posting back to the server - looking at it you are passing raw HTML into some parameters on the object:
event.IsActive = row.find(".IsActive").find("span").html();
At best, event.IsActive will be the string "True" (or False), rather than an actual boolean that your model is expecting. You would be better off changing that line to something like:
event.IsActive = row.find(".IsActive").find("input").is(":checked");
And then confirm what is being sent to the server in the network tab of your browser.

KnockoutJS in MVC DataTable Delete Function

I have followed a tutorial that I found at http://www.dotnetcurry.com/aspnet-mvc/933/knockoutjs-aspnet-mvc-tutorial-beginner. The tutorial is great and covers add and update however there are no click handlers included for delete or cancelling the update.
I tried to follow the same pattern the author provided for saving data and I created a function to delete, however this does not work.
function deleteData(currentData) {
var postUrl = "";
var submitData = {
concerns_id: currentData.concerns_id(),
concerns_description: currentData.concerns_description(),
};
if (currentData.concerns_id > 0) {
postUrl = "/concerns/delete"
}
$.ajax({
type: "POST",
contentType: "application/json",
url: postUrl,
data: JSON.stringify(submitData)
}).done(function (id) {
currentData.concerns_id(id);
}).error(function (ex) {
alert("ERROR Deleting");
})
};
This is the table:
<table class="table">
<tr>
<th>concerns_id</th>
<th>concerns_description</th>
<th></th>
</tr>
<tbody data-bind="foreach: ConcernCollection">
<tr data-bind="template: { name: Mode, data: $data }"></tr>
</tbody>
</table>
The Templates:
<script type="text/html" id="display">
<td data-bind="text: concerns_id"></td>
<td data-bind="text: concerns_description"></td>
<td>
<button class="btn btn-success kout-edit">Edit</button>
<button class="btn btn-danger kout-delete">Delete</button>
</td>
</script>
<script type="text/html" id="edit">
<td><input type="text" data-bind="value: concerns_id " /></td>
<td><input type="text" data-bind="value: concerns_description" /></td>
<td>
<button class="btn btn-success kout-update">Update</button>
<button class="btn btn-danger kout-cancel">Cancel</button>
</td>
</script>
Full JS without the Delete Function that I tied to add:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/concerns/GetConcerns",
}).done(function (data) {
$(data).each(function (index, element) {
var mappedItem =
{
concerns_id: ko.observable(element.concerns_id),
concerns_description: ko.observable(element.concerns_description),
Mode: ko.observable("display")
};
viewModel.ConcernCollection.push(mappedItem);
});
ko.applyBindings(viewModel);
}).error(function (ex) {
alert("Error");
});
$(document).on("click", ".kout-edit", null, function (ev) {
var current = ko.dataFor(this);
current.Mode("edit");
});
$(document).on("click", ".kout-update", null, function (ev) {
var current = ko.dataFor(this);
saveData(current);
current.Mode("display");
});
$(document).on("click", "#create", null, function (ev) {
var current = {
concerns_id: ko.observable(0),
concerns_description: ko.observable(),
Mode: ko.observable("edit")
}
viewModel.ConcernCollection.push(current);
});
function saveData(currentData) {
var postUrl = "";
var submitData = {
concerns_id: currentData.concerns_id(),
concerns_description: currentData.concerns_description(),
};
if (currentData.concerns_id && currentData.concerns_id() > 0) {
postUrl = "/concerns/Edit"
}
else {
postUrl = "/concerns/Create"
}
$.ajax({
type: "POST",
contentType: "application/json",
url: postUrl,
data: JSON.stringify(submitData)
}).done(function (id) {
currentData.concerns_id(id);
}).error(function (ex) {
alert("ERROR Saving");
})
}
});
Any help or guidance would be apprenticed this is my first time working with Knockout.js
Thanks,
I'm not gonna lie, your code is a little hard to follow. I really don't think you're getting the full knockout experience. I put together a tiny little demo to show you just how you can use knockout to add/remove items from a list and display them.
Knockout should be used for data-binding. You should honestly never need to use jQuery to attach listeners by class. That is how your code becomes spaghetti.
While your question doesn't ask it, I strongly recommend visiting http://learn.knockoutjs.com/ before continuing your tutorial much further.
I hope this helps!
function ViewModel() {
var self = this;
self.Items = ko.observableArray();
self.DeleteRow = function(row) {
// Your ajax call here
self.Items.remove(row);
}
self.AddRow = function() {
self.Items.push("Added Item at " + new Date());
}
self.LoadFakeData = function() {
// Put ajax calls here
for (i = 0; i < 10; i++) {
self.Items.push("Item " + i);
}
}
self.Load = function() {
self.LoadFakeData();
}
self.Load();
}
ko.applyBindings(new ViewModel())
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="foreach: Items">
<span data-bind="text: $data"></span>
<span data-bind="click: $parent.DeleteRow">X</span>
<br>
</div>
<hr>
<span data-bind="click: AddRow">Add Row</span>

Asp.Net MVC4 Return Date and Time from Controller to View

I am working with Asp.Net MVC4, I need to retrieve the date and time from the server and not the client. To restore them when I must click a button in the view, for example the name of the button "Nuevo" and from the view so I defined, the event is called by javascript in Action define the controller (Home) and ActionResult (Nuevo):
<script type= "text/javascript">
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({ }),
success: function () {}
});
}
</script>
On receipt the data controller in the New ActionResult as follows:
[HttpPost]
public ActionResult Nuevo()
{
Persona persona = new Persona();
persona.Fecha = DateTime.Now;
persona.Hora = DateTime.Now;
return View(persona);
}
This is my view, I use typed views:
#model MvcJavaScript.Models.Persona
<script type= "text/javascript">
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({}),
success: function (data) {
}
});
}
</script>
<h2>Registro persona</h2>
#using (Html.BeginForm("", "", FormMethod.Post, new { id = "formPersona" })){
<table cellpadding="4" class="td.headerTabsColor">
<tbody>
<tr>
<td><label>Fecha : </label>#Html.TextBoxFor(u => u.Fecha, new { sololectura = true })</td>
</tr>
<tr>
<td><label>Sexo : </label>#Html.TextBoxFor(u => u.Sexo, new { style = "width:225px", sololectura = false })</td>
</tr>
<tr>
<td><label>Hora : </label>#Html.TextBoxFor(u => u.Hora, new { sololectura = true })</td>
</tr>
</tbody>
</table>
}
What I need to do is to insert a new record (by clicking on the button "Nuevo") I load the default server time and date in different textbox.
Running this example enters the New ActionResult but to return to the data to view the TextBox is void, I tried other fields and the same result.
Any suggestions or help with this problem.
regards
Ricardo
There are basically two different routes you usually take when creating an AJAX action: letting the server render the HTML, or just sending data back to the browser and let the browser render the HTML. The code you have posted is a mixture of the two - that's why it's not working. The jQuery AJAX call is expecting JSON data back from the server, but the server is sending the HTML rendered by the Views\Home\Nuevo.cshtml view. Let's look at what these two different approaches might look like.
Server-Rendered Approach
You need to add an HTML element that will display the result. We will call it NuevoResult. And we also need some code that will put the response there. The easiest way is jQuery's .html() method.
<div id="NuevoResult"></div>
<script type= "text/javascript">
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
// ... also 'contentType' and 'data' if you're actually sending anything to the server...
dataType: 'html',
success: function (data) {
$('#NuevoResult').html(data);
}
});
}
</script>
We also need a Views\Home\Nuevo.cshtml view for the server to render. It might look like:
#model MyCoolNamespace.Persona
<h3>New person created!</h3>
<p>Created on #string.Format("{0:d}", Model.Fecha) at #string.Format("{0:t}", Model.Hora).</p>
This is all the HTML we want to return from this action. We don't want it to be wrapped in any layout. To do this, we need to make sure we return PartialView(persona) instead of return View(persona).
Browser-Rendered Approach
For the browser rendered approach, we'll go ahead and have the HTML ready on the browser, but hidden. We'll fill it in with the correct information and display it when we receive a response from the server.
<div id="NuevoResult" style="display:none">
<h3>New person created!</h3>
<p>Created on <span id="Fecha"></span> at <span id="Hora"></span>.</p>
</div>
<script type= "text/javascript">
function ParseJSONDateTime(value) {
// from http://stackoverflow.com/questions/206384/how-to-format-a-json-date/2316066#2316066
return new Date(parseInt(value.substr(6)));
}
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
// ... also 'contentType' and 'data' if you're actually sending anything to the server...
dataType: 'json',
success: function (data) {
$('#Fecha').text(ParseJSONDateTime(data.Fecha).toLocaleDateString());
$('#Hora').text(ParseJSONDateTime(data.Hora).toLocaleTimeString());
$('#NuevoResult').show();
}
});
}
</script>
And then in the MVC action, use return Json(persona) to send the data back to the browser.
A few more notes...
The .NET DateTime structure holds both date and time information, so there's no need to have separate Fecha and Hora properties. Consider replacing with a single CreatedTimestamp property.
If you're still having trouble, Firefox's Firebug extension, Internet Explorer's Developer Tools, and Chrome's Developer Tools can be very helpful in figuring out what is wrong, allowing you to see exactly what was returned from the server.
Hi if i'm correct the problem is that the textbox values remain empty after you fired the function. The reason behind this is that your javascript function returns the data in the
success : function() {} part.
So what you have to do is return some kind of Json and then place the correct values in the textbox.
Javascript:
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
success: function(data) {
//Do stuff with your data
}
});
c#:
[HttpPost]
public ActionResult Nuevo()
{
Persona persona = new Persona();
persona.Fecha = DateTime.Now;
persona.Hora = DateTime.Now;
return Json(persona, JsonRequestBehavior.AllowGet);
}
This is my view, I use typed views:
#model MvcJavaScript.Models.Persona
<script type= "text/javascript">
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({}),
success: function (data) {
}
});
}
</script>
<h2>Registro persona</h2>
#using (Html.BeginForm("", "", FormMethod.Post, new { id = "formPersona" })){
<table cellpadding="4" class="td.headerTabsColor">
<tbody>
<tr>
<td><label>Fecha : </label>#Html.TextBoxFor(u => u.Fecha, new { sololectura = true })</td>
</tr>
<tr>
<td><label>Sexo : </label>#Html.TextBoxFor(u => u.Sexo, new { style = "width:225px", sololectura = false })</td>
</tr>
<tr>
<td><label>Hora : </label>#Html.TextBoxFor(u => u.Hora, new { sololectura = true })</td>
</tr>
</tbody>
</table>
}
If you are returning just a json object from the post call, you can write the success function in you ajax post back like below.
success : function(data) {
$('#inputFecha').html(data.Fecha);
$('#inputHora').html(data.Hora);
}
However if you are returning the view itself (which it looks like from your code), write the success function like this
success : function(data) {
$('#formContainer').html(data); // where formContainer is the control containing your form - may be an html body.
}
EDIT
since you have posted the view, change the Html.TextBoxFor lines for Fecha and Hora like below and use the success function given further below,
#Html.TextBoxFor(u => u.Fecha, new { sololectura = true, id="inputFecha" })
#Html.TextBoxFor(u => u.Hora, new { sololectura = true, id="inputHora" })
success : function(data) {
$('#inputFecha').html(data.Fecha);
$('#inputHora').html(data.Hora);
}
You can try this:
C#
[HttpPost] // Why do you need to use POST method?
public JsonResult Nuevo()
{
return Json(new { Fecha = DateTime.Now, Hora = DateTime.Now });
// if use get: return Json(object, JsonRequestBehavior.AllowGet);
}
HTML:
<button id="button-nuevo">Nuevo</button>
<h2>Registro persona</h2>
#using (Html.BeginForm("", "", FormMethod.Post, new { id = "formPersona" })){
<input type="hidden" id="url-nuevo" value="#Url.Action("Nuevo", "Home")" />
<table cellpadding="4" class="td.headerTabsColor">
<tbody>
<tr>
<td><label>Fecha : </label>#Html.TextBoxFor(u => u.Fecha, new { #readonly=true })</td>
</tr>
<tr>
<td><label>Sexo : </label>#Html.TextBoxFor(u => u.Sexo, new { style = "width:225px", sololectura = false })</td>
</tr>
<tr>
<td><label>Hora : </label>#Html.TextBoxFor(u => u.Hora, new { #readonly = true })</td>
</tr>
</tbody>
</table>
}
JS
function dateFormat(d) {
var date = d.getDate(),
month = d.getMonth() + 1,
year = d.getFullYear();
retur (month > 9 : month ? '0' + month) + "/" + (date > 9 : date ? '0' + date) + "/" + year;
}
$('#button-nuevo').bind('click', function(event) {
var $formContext = $('#formPersona');
$.post($('#url-nuevo').val(), {}, function(data){
//UPDATE
var fecha = new Date(parseInt(data.Fecha.substr(6, 13)));
var hora = new Date(parseInt(data.Hora.substr(6, 13)));
$formContext.find('#Fecha').val(dateFormat(fecha));
$formContext.find('#Hora').val(dateFormat(hora));
}, "json");
});
Update based on this answer

How can I return the HTML from MVC controller to a div in my view

I'm trying to return the generated HTML string to the view to dynamically generate a HTML table with results. I'm not able to get the returned HTML string any suggestions and help is greatly appreciated.
Here is my Controller code
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);
}
I'm trying to grab this returned result in jquery like this
$('#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(); }
}
});
});
Finally Below is the CSHTML for the form. Here I'm reading a file from a form with a button type submit
<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>
Thanks for your time and really appreciate your help. Kind Regards!!!
you can return HTML from action like this,
return Content(html, "text/xml");
It sounds as if your form is still submitting a normal postback, so any asynchronous calls that you're doing are being lost.
Try preventing the default form submission taking place with the following:
$('#tramsView').live('click', function (evt) {
evt.preventDefault();
// ... rest of your code
});
Incidentally, in this case, if all you're doing is updating the html on your #TramsViewFrame, you could just use the slightly simpler $.load() method:
$('#tramsView').live('click', function (evt) {
evt.preventDefault();
$('#TramsViewFrame').load('/Booking/ValidateTrams');
});
Make these changes
Give the attribute HttpPost on top of your controller
[HttpPost]
public ActionResult ValidateTrams()
return the string as Json like this from the controller.
return Json(new { success = html });
Finally change your dataType from jsonp to 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: If you are using the latest version of jQuery (1.7+), please change the .live handler to .on handler. Not mandatory :)
In your controller since you are using ajax post you need to return as JSON it would be something like this
return Json(html);
i think this is another way relevant to your scenario 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
instead of storing in "string" store html codes in following format:
HtmlString s = new HtmlString("<html coding/>");
ViewData["Id_as_per_your_choice"] = s;
return View("page_you_want to_respond");
then place "<%: ViewData["Id_Same_as_that_in_above_code"] %>" where ever you want that html code to appear......simple.....
but make initial value of Viewdata as null in "index()"method so that code doesnot appear on page load....

Resources