Partial View ignoring data set and not displaying - c#

I am developing an application in ASP.NET MVC. I am working on a page that takes some user entered values and then gets a data set from them using a stored procedure. My preference is that the data is entered on the same page as it is displayed, so I am using AJAX and partial views to accomplish this. My code worked perfectly with a dummy set of simple data (simple string) but now that I am using a more advanced data set (Ienumerable) it no longer displays the partial view.
Here is part of my view (textboxes where data is entered are hidden for length purposes):
<!--SEARCH RESULTS PARTIAL FILLED BELOW-->
<div id="search-results">
</div>
<!---->
<script>
function getSearchResults() {
var SqlViewModel = {
//assign textboxes to values to pass to controller (hidden)
}
$.ajax({
type: "POST",
data: JSON.stringify(SqlViewModel),
dataType: "json",
contentType: "application/json",
url: "/Sql/Search/",
success: function(result) {
$('#search-results').html(result);
}
}); }
</script>
I grab the data from the textboxes, and then pass those values to my "Search" controller method using my ajax. (values are all passed correctly using SqlVieWModel)
Controller method:
[HttpPost]
public ActionResult Search(SqlViewModel sT)
{
//code for stored procedure
var sql = //get stored procedure and parameters
SqlPartialViewModel obj = new SqlPartialViewModel();
obj.SqlData = sql; //obj.SqlData is of type IEnumerable<Get_Result>
return PartialView("_SearchResultsPartial", obj);
SqlPartialViewModel definition:
public class SqlPartialViewModel
{
public IEnumerable<Get_Result> SqlData { get; set; }
}
Finally, I attempt to simply get this data to display in my partial view (_SearchResultssPartial.cshtml):
#model SqlPartialViewModel
<table>
<tr>
<th>//Display stuff</th>
</tr>
#foreach(var result in Model.SqlData)
{
<tr>
<td>//Display stuff</td>
</tr>
}
Nothing displays, and I receive no errors.

In you Ajax call, you're expecting a json result from the server:
$.ajax({
type: "POST",
data: JSON.stringify(SqlViewModel),
dataType: "json", <---- HERE
contentType: "application/json",
url: "/Sql/Search/",
success: function(result) {
$('#search-results').html(result);
}
});
But when you return a PartialView from an ActionResult, you're returning html type, not jsontype.
Just change the dataType to "html" or remove that line (so javascript will try to interpret by itself).

Related

Pass Model and Variables with AJAX

A partial view (_AddItem.cshtml) is called from the main view (Category.cshtml) in order to add existing items to the page on load.
I'm now adding AJAX so that an item can be added, to the page, by the user at the click of a button. When the form is subsequently submitted the item will be added to the model.
The partial view relies on the category model (activeCategoryModel) and two variables. Currently, these are successfully being passed from the view in the following way:
Category.cshtml
#Html.Partial(
"_AddItem",
activeCategoryModel,
new ViewDataDictionary(ViewData) { { "itemIndex", itemIndex }, { "itemLabel", itemLabel } }
);
My question is how can I pass the model (activeCategory) and these two variables when using AJAX? Below is the code I've started writing for the AJAX post:
Button and inputs added to view (Category.cshtml)
<input id="add-item-label" type="text" />
<input id="nextItemIndex" type="hidden" value="#activeCategoryModel.Items.Count" />
<button id="add-item" type="button">Add Item</button>
AJAX post added in javascript
This is not necessary fully functional code, I've just attempted to write an AJAX post with the variables in the 'data' parameter.
$("#add-item").click(function () {
var itemIndex = $("#nextItemIndex").val();
var itemLabel = $("#add-item-label").val();
$.ajax({
type: "POST",
url: '#Url.Action("_AddItem")',
data: '{{itemIndex: ' + itemIndex + '}, {itemLabel: ' + itemLabel + '}}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
$("#nextItemIndex").val($("#nextItemIndex").val() + 1);
},
error: function () {
alert("Error while adding item");
}
});
return false;
});
Partial view call added to Controller
I think this is where the model and variables need to be included in the partial view call.
public ActionResult _AddItem(string itemIndex, string itemLabel)
{
return PartialView();
}
Partial View (_AddItem.cshtml)
This has not been changed for the AJAX post.
#model CategoryModel
#{ int i = (int)ViewData["itemIndex"];}
#{ string l = (string)ViewData["itemLabel"];}
...
There are different ways in this case,
Example : Html.RenderPartial directly rendered partial action without ajax.
If you want to use Ajax to call partialView , you must be render
Html. Because PartialView returned Html.
I think the most important value in Ajax request is dataType and
the second important point is added returned html data in a div element
jQuery("#add-item").click(function () {
var dItemIndex = 1; //$("#nextItemIndex").val();
var dItemLabel = "Text"; // $("#add-item-label").val();
$.ajax({
type: "POST",
url: '#Url.Action("_AddItem","Home")',
data: { itemIndex: dItemIndex, itemLabel: dItemLabel },
dataType: "html",
//contentType: "application/json; charset=utf-8",
success: function (d) {
console.log("Success");
$("#partialData").html(d);
**// Create div in cshtml Page
// <div id="partialData"></div>**
},
error: function () {
alert("Error while adding item");
}
});
return false;
});
At the controller side you can read parameters and fill in the content and send the PartialView as follows.
public ActionResult _AddItem(string itemIndex, string itemLabel)
{
ViewData["itemIndex"] = itemIndex;
ViewData["itemLabel"] = itemLabel;
return PartialView(new CategoryModel { Id = 5, Text = "Sample 5" });
}

Accessing request from external url

Hi I'm new to umbraco MVC. I'm using version 7. What I'm trying to do is following:
An External page www.ble1.com is posting to my page www.le2.com/recieve when that happens ble1 is posting to the page and in the browser dev tools I can see the Form Data name of the parameter (tok) and some encoded string.
Now I want to take this data and send it to the controller code behind the macro running on my page www.le2.com/recieve. How would this be possible? I'm used to workin in asp.NET where I have the pageLoad function in code behind but I'm confused how to tackle this in Umbraco MVC.
What I have done so far is Create cshtml:
#inherits Umbraco.Web.Macros.PartialViewMacroPage
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '../../../umbraco/surface/land/Login',
data: JSON.stringify({}),
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (data) {
alert(data.d);
}
});
});
</script>
My Controller
public JsonResult Login()
{
//Don't know what to do here!!!!
//Everything that I have tryed has failed. Calling Request....etc.
}
I have never worked with Umbraco, but I have with MVC.
You Login method is not marked to receive POST requests. You need to use the attribute [HttpPost]
Your Login method does not have any Arguments, so, even if you fix your issue #1, it will not get any data.
So, first, you need some data in your Action Method, so you either need a ViewModel or a set or parameters, this is a ViewModel sample:
public class MyLoginViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
Now we use that ViewModel in the Action Method:
[HttpPost]
public JsonResult Login(MyLoginViewModel model)
{
if (ModelState.IsValid)
{
// Do something here (probably use Umbraco internal's authorization layer)
var valid = (model.UserName == "user" && model.Password == "pwd");
if (valid)
return Json(new { code = 0, message = "OK" });
else
return Json(new { code = 10, message = "User/Password does not match" });
}
// Model is invalid, report error
return Json(new { code = -1, message = "invalid arguments" });
}
It is a very naive example, it makes sure the ViewModel is Valid, if it is, it performs the actual login logic, in this sample is just checks 2 values and returns the status.
In the HTML page, you could have:
<input type="text" id="userName" />
<input type="text" id="password" />
<button id="login">Login</button>
<script>
$(document).ready(function () {
$("#login").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/home/Login',
data: JSON.stringify({ UserName: $('#userName').val(), Password: $('#password').val() }),
dataType: 'json',
success: function (data) {
alert(data.message);
},
error: function (data) {
alert("An error has occurred while processing your request");
}
});
})
});
</script>
Again, very a naive example.
I hope it gives you enough information to adapt it to Umbraco.
Sorry I cannot give you Umbraco specific information.

How to serialize model, pass it to MVC controller in ajax request

I'm trying to pass my page's model to my controller for processing.
After processing the information, I want to update the div of id "savedText" to display "Billing Information saved successfully."
I have this in my view
function testingFunction() {
var obj = $('testForm').serialize();
$.ajax({
url: '#Url.Action("TestingFunction", "BuildGiftCard")',
dataType: 'json',
success: function (result) {
$("#savedText").html(result);
},
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(obj)
});
return false;
}
and I have this in my controller:
[HttpPost]
public JsonResult TestingFunction(PurchaseModel model)
{
return Json("Billing information saved successfully.");
}
what am I doing wrong?
When "inspecting element" in chrome, in the network tab, it's saying that my controller method isn't found.
Also, it's important for me to get the entire model from the view into the controller's function (TestingFunction in this case) so that I can get the form information and save it. I'm trying the .serialize() function but that results in obj = (empty string).
Three things:
$('testForm') should probably be $('.testForm') or $('#testForm'). As it is you're trying to select a <testForm></testForm>.
If you're just sending the form, it doesn't need to be json.
Try doing a post request:
$.ajax({
url: '#Url.Action("TestingFunction", "BuildGiftCard")',
dataType: 'json',
success: function (result) {
$("#savedText").html(result);
},
data: $('#testForm').serialize(),
type: 'POST'
});

Pass Model from View To Controller Using ActionLink

what is the best way to pass model data from View to Controller using actionLink. actually my action link is download link and i want to pass report model as it contains datatable information.
private void DownloadReport(ReportModel rptModel)
{
// want to recieve report model here.
// to do so.
}
An ActionLink is ultimately just an anchor element.
Instead, use a form with an anchor element that submits the form.
The corresponding controller method would accept your ReportModel.
You can use Ajax post method for the same..
For example in your view :-
<script type="text/javascript">
var rptModel = {
val1: "val1",
....
};
$.ajax({
url: '/NameOfController/DownloadReport,
type: 'POST',
data: JSON.stringify(rptModel),
contentType: 'application/json; charset=utf-8',
success: function (data.success) {
alert(data);
},
error: function () {
alert("error");
}
});
</script>
And this whatever you pass from view you will get in your action method.

Pass a collection to MVC controller via jquery

I'm using ASP.NET MVC3 with Jquery. I'm trying to pass my form elements back to the controller using something like this (Please note I removed success and error code for simplicity):
var formElements = $("#myForm").serialize();
$.ajax({
type: "POST",
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: {collection: formElements},
success:
error:
dataType: "json"
});
My question is what should the parameter in my controller method look like:
Here is my controller method:
public ActionResult SubmitChanges(WHAT GOES HERE?)
{
}
So what I'm really looking for is what should be the type of the parameter going into the controller method? I want to be able to retrieve the values of the form elements in the controller.
So here is what I did. I have about 20-30 elements on my form so I really didn't want to have to turn each one into a parameter or list them all out in the collection.
In the jquery, I did the following:
var formElements = $("#myForm").serialize();
$.ajax({
type: "POST",
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: { parms: formElements },
success:
error:
dataType: "json"
});
It then goes into my controller as a string:
public ActionResult SubmitChanges(string parms)
I then found a function to parse that string (seems to be working)
NameValueCollection qscoll = HttpUtility.ParseQueryString(parms);
This seems to work without listing out all of the form elements.
Assuming your form elements all correspond to your model (let's say it's MyModel), then it should simply be:
public ActionResult SubmitChanges(MyModel model)
{
}
MVC default model binding will do the rest :).
Make sure you change your data definition in the jQuery ajax method though, you've already serialized it. Just do:
data: formElements,
I'm assuming the following in your jQuery ajax method is a copy and paste error?
success:
error:
If it's not, then make sure you either remove it, or change them to:
success: function (result) {
//do something
},
error: function () {
//do something on error
}
The problem is that their is no model that corresponds to my form
elements.
Then you can have this:
public ActionResult SubmitChanges(int id, string name)
{
}
And then pass in the individual items:
var o = {
id = $("#id_elem_id").val(),
name = $("#name_elem_id").val()
}
$.ajax({
type: "POST",
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: JSON.stringify(o),
success:
error:
dataType: "json"
});
where id_elem_id and name_elem_id are the ids of your html elements. And add any additional parameters you need, just follow along.
You were almost there. Just get rid of the brackets around your data parameter:
var formElements = $('#myForm').serialize();
$.ajax({
type: 'POST',
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: formElements,
success: function(result) {
// handle the success of the AJAX request
},
error: function() {
// an error occurred
}
});

Categories

Resources