asp.net MVC - AJAX model to controller - asp.net

Is it possible to pass my view Model to the controller, using ajax, without 'rebuilding' the object?
I have my view:
#using Project.Models
#model InfoFormulaireEnqueteModele
#section Style{
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />}
#section Scripts{
#Scripts.Render("~/bundles/autocomplete")
#Scripts.Render("~/bundles/timeentry")
<script type="text/javascript">
var $status = $('#status'),
$commentBox = $('#commentBox'),
timeoutId;
var model = #Model; //<- something's wrong here
$commentBox.keypress(function () {
$status.attr('class', 'pending').text('changes pending');
// If a timer was already started, clear it.
if (timeoutId) clearTimeout(timeoutId);
var r = '';
// Set timer that will save comment when it fires.
timeoutId = setTimeout(function () {
var test = $('#commentBox').val();
// Make ajax call to save data.
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: '/Enquete/IndexPartial/',
contentType: "application/json"
}).done(function (res) {
$("#SomeDivToShowTheResult").html(res);
});
$status.attr('class', 'saved').text('changes saved');
}, 1000);
return r;
});
</script>
Controller:
[HttpPost]
public PartialViewResult IndexPartial(InfoFormulaireEnqueteModele m)
{
return PartialView("_IndexPartial", m);
}
I am able to reach my controller, but my model (m) has only null values once in the controller.. The values were set in the controller before being sent to the view.

In your action method speciy [FromBody] as below
[HttpPost]
public PartialViewResult IndexPartial([FromBody] InfoFormulaireEnqueteModele m)
{
return PartialView("_IndexPartial", m);
}

You should do it like this:
var model = #Html.Raw(Json.Encode(#Model));
That's how you convert your model to json and pass it to js

Related

Send string from View to Controller ASP.Net mvc

So we are pretty new to ASP.Net MVC
We have this method that runs when we click on a button in our view. We would like to send the date string to our controller. How can we achieve this?
$('#calendar').fullCalendar({
//weekends : false
dayClick: function(date) {
console.log(date.format());
}
})
This is our controller
[HttpPost]
public IActionResult Booking(string test)
{
var booking = new Booking();
//booking.Date = dateTime;
Console.WriteLine(test);
var viewModel = new BookingsideViewModel
{
Subjects = new[] {"Matematik", "Dansk", "Engelsk"},
Booking = booking
};
return View();
}
you can do it using ajax call,
$.ajax({
url: '#Url.Action("Booking")',
data: { 'test' : date },
type: "post",
cache: false,
success: function (response) {
console.log("success");
},
error: function (error) {
console.log(error.message);
}
});
you can also write url like this:
url:"/ControllerName/ActionName"

View not loaded when ActionResult is called from AJAX in ASP.NET MVC

I have called actionresult function from JavaScript using AJAX when a button is clicked:
<script type="text/javascript">
$('.btn-SelectStudent').on('click', function () {
$('input:radio').each(function () {
if ($(this).is(':checked')) {
var id = $(this).val();
$.ajax({
url: '#Url.Action("ParseSearchLists", "Upload")',
data: { studentId: id }
}).success(function (data) {
alert('success');
});
}
else {
// Or an unchecked one here...
}
});
return false;
})
</script>
Inside the UploadController.cs:
[HttpPost]
public ActionResult ParseSearchLists(int studentId)
{
SearchModel searchModel = ApplicationVariables.searchResults.Where(x => x.StudentId == studentId).ToList().First();
TempData["SearchModel"] = searchModel;
return RedirectToAction("UploadFile", "Upload");
}
public ActionResult UploadFile()
{
searchModel = TempData["SearchModel"] as SearchModel;
return View(searchModel); //debug point hits here.
}
Inside UploadFile(), I have returned View and it should load another view. But I get only "success" in alert but no new view is loaded. I assume, view should be loaded.
You're making an "AJAX" call to the server, meaning your request is running outside of the current page request and the results will be returned to your success continuation routine, not to the browser's rendering engine. Essentially the data parameter of that routine is probably the entire HTML response of your UploadFile view.
This is not what .ajax is used for. It is for making asynchronous requests to the server and returning data (usually JSON or XML) to your javascript to be evaluated and displayed on the page (this is the most common use anyway).
I can't see your HTML, but wouldn't you be better off just using an <a> anchor (link) tag and sending your student ID on the query string? It's hard to tell what you are attempting to do but your views' HTML (.cshtml) will never be displayed using the code you have now.
It seems, you are not loading view returned to div on ajax success. replace #divname with your div in your code in below code. i hope this helps to resolve your issue
<script type="text/javascript">
$('.btn-SelectStudent').on('click', function () {
$('input:radio').each(function () {
if ($(this).is(':checked')) {
var id = $(this).val();
$.ajax({
url: '#Url.Action("ParseSearchLists", "Upload")',
dataType: "html",
data: { studentId: id }
}).success(function (data) {
$('#divName').html(data); // note replace divname with your actual divname
});
}
else {
// Or an unchecked one here...
}
});
return false;
})
</script>
[HttpPost]
public ActionResult ParseSearchLists(int studentId)
{
SearchModel searchModel = ApplicationVariables.searchResults.Where(x => x.StudentId == studentId).ToList().First();
return View("UploadFile",searchModel); //debug point hits here.
}

MVC 5 JsonResult returns html?

I have been following this tutorial https://www.youtube.com/watch?v=c_MELPfxJug regarding ajax and JsonResult in HomeController
I did the tutorial, however for some reason the controller is returning Html and not json
I did not change one line of code, but it's failing with parseError on the javascript side.
when i look at the response i see an html page, not a json object.
Controller code:
public JsonResult DoubleValue(int? Value)
{
if (!Request.IsAjaxRequest() || !Value.HasValue)
{ return null; }
else
{
int DoubleValue = Value.Value * 2;
var ret = new JsonResult
{
Data =
new { DoubleValue = DoubleValue }
};
return ret;
}
}
cshtml:
#using (Html.BeginForm())
{
#Html.TextBox("txtAmount",0)
<button id="btnDoubleValue">DoubleIT</button>
<div id="lblMessage"></div>
}
#section Scripts{
<script type="text/javascript">
$(function () {
$('#btnDoubleValue').on('click', function() {
$.ajax({
type: 'POST',
url: '#Html.Action("DoubleValue")',
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
}).success(function (data) {
var t = data;
$('#txtAmount').val(data.DoubleValue);
}).error(function (x, o, e) {
$('#lblMessage').html('error was found: ' );
});
return false;
})
});
</script>
}
found the error
I was using Html.Action and not Url.Action -> just human error I suppose
from the reference:
Html.Action - returns the result as an HTML string.
It works now
$.ajax({
type: 'POST',
url: '#Url.Action("DoubleValue")', //<--- Url.Action
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
I guess this must be the default error page, you are probably getting a 500 response and you must use the Network tab of your browser to see the real problem.
In your browser open developer tools using F12 key and navigate to Network tab.
Make the appropriate actions to do the ajax request (click on that button)
Click on the request row
Navigate to Response tab.
From there you can watch the real request your ajax does and the response from the server.

Change UpdateTargetId of Ajax.BeginForm() dynamically based on form submission result

I'd appreciate if someone could help.
I want to return different partial views based on user type:
[HttpPost]
public ActionResult Edit(ContractModel model)
{
if(ModelState.IsValid)
{
if (curUser.IsInputer) { .... return View("Contracts");}
else if(curUser.IsAuthorizer) { ..... return View("Details");}
}
return PartialView(model);
}
View:
#{
string updateRegion = "";
if (curUser.IsInputer)
{
updateRegion = "content";
}
else if (curUser.IsAuthorizer)
{
updateRegion = "mainPane";
}
}
<script>
function returnViewOnFailure(result) { //not firing on submission failure
$("#mainPane").html(result);
}
</script>
#using (Ajax.BeginForm("Edit", new AjaxOptions() { UpdateTargetId = updateRegion,
InsertionMode = InsertionMode.Replace,
OnFailure = "returnViewOnFailure" }))
{.........}
The problem is when ModetState.IsValid= false my function returnViewOnFailure is not firing.
I would like UpdateTargetId be "mainPane" if form submission fails (regardless of user type), otherwise it should depend on curUser.
EDIT:
So, as advised I'm using ajax call to sumbit the form:
<script>
var form = $('#contract_form');
form.submit(function (ev) {
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
$("#content").html(data);
//How to check ModelState.IsValid and show errors?
}
});
ev.preventDefault();
});
Because the validation is done serverside you can set the statuscode of the response (Controller.Response).
If the validation does not succeed set it to 500 (internal server error) so the ajax.onfailure gets called. Put the validationerror logic (replacing divs content) in there. Or maybee you can even change the updatetargetid in the onfailure (by javascript).

Viewdata not showing in partial view

Hi guys i have controller which returns a partial view, the controller is called by ajax script. The partical view has no problem showing viewdata first time, But when ajax script is invoked second time the partical view does not update it self with new viewdata.
code for controller
[HttpGet]
public ActionResult getPart(int id)
{
ViewData["partical"] = id;
return PartialView("test");
}
code for partial view
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<PovertyBayHotel.Models.testmodel>" %>
<p>just a test</p>
<%: ViewData["partical"]%>
and the ajax which call the controller
<script type="text/javascript">
$(document).ready(function () {
$("#DropDown").change(function () {
var course = $("#DropDown > option:selected").attr("value");
$.ajax({
type: 'GET',
url: '/Reservation/getPart',
data: { id: course },
success: function (data) {
$('#ExtraBox').replaceWith(data);
}
});
});
});
</script>
Might be a caching issue. Try HTTP POST instead of GET or set the ifModified and cache options to false as below:
$("#DropDown").change(function () {
var course = $("#DropDown > option:selected").attr("value");
$.ajax({
type: 'GET',
ifModified: false,
cache: false,
url: '/Reservation/getPart',
data: { id: course },
success: function (data) {
$('#ExtraBox').replaceWith(data);
}
});
Also, try to debug your code and see really what is going on.
Edit:
The problem has been solved by changing $('#ExtraBox').replaceWith(data); with $('#ExtraBox').html(data);.

Resources