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" });
}
Related
I have a List (List) of Model objects which is presented in a view. I would like to add to that list without refreshing the page - therefore i thought Ajax is a great soloution. Im currently having a hard time getting it working.
My view is rendering a PartialView which contains the list.
Can somebody give me a hint how to pass a list to the controller and then back to the view without updating the whole page?
I hope my question makes sense.
/chris
EDIT:
I've been trying with JQuery. Looks like this:
<script>
$(document).ready(function () {
$("#btnSave").click(function () {
$.ajax(
{
type: "POST", //HTTP POST Method
url: "/Video/Index", // Controller/View
data: { //Passing data
testString: $("#txtArea").val(),
videoID: '#(Model.Video.iVideo_ID)',
taskID: document.getElementById('dropVal').value
}
}).success(function () {
$("#proever").load("/Video/Index");
});
})
})
With this method i get to HttpPost method in my controller. And i pass the parameters into it succesfully.
[HttpPost]
public ActionResult Index(CommentViewModel viewModel)
{
System.Diagnostics.Debug.WriteLine(viewModel.testString);
System.Diagnostics.Debug.WriteLine(viewModel.videoID);
System.Diagnostics.Debug.WriteLine(viewModel.taskID);
viewModel.testString = "new text string";
return View(viewModel);
}
The problem is now that i can't get the updated viewmodel back to the view.. What am i doing wrong?
In this example I don't update the list but just a test string to see if i can get it updated back to the view..
For those who's interested I solved the problem like this:
<script>
$(document).ready(function () {
$("#btnSave").click(function () {
$.ajax(
{
type: "POST", //HTTP POST Method
url: "/Video/AddComment", // Controller/View
data: { //Passing data
//Reading text box values using Jquery
sComment: $("#txtArea").val(),
videoID: '#(Model.Video.iVideo_ID)',
taskID: document.getElementById('dropVal').value
}
}).success(function () {
console.log("good");
var txt = document.getElementById('txtArea').value;
console.log(txt);
var taskId = document.getElementById('dropVal').value;
var taskCont = $("#dropVal option:selected").text();
var taskContNum = Number(taskCont) - 1
console.log(taskCont);
var node = document.createTextNode(txt);
var para = document.createElement("div");
para.appendChild(node);
document.getElementById('taskPalace').appendChild(para);
document.getElementById('cola-' + '' + taskContNum).appendChild(para);
document.getElementById('txtArea').value = "";
});
})
})
So if the request succeeds without any errors in the HttpPost method it adds the comment to the database(through the HttpPost) and the jquery adds it to the view.
You need to use persistent data store in your case. Currently, your async post request will change the view model data but data is lost in subsequent http requests when you try to load the view with .load(...) jquery function.
1- Send async request to http post controller action to change the data in db store for example.
2- Read the view model data from db in http get index action. ($("#proever").load("/Video/Index"))
You can try this:
$(document).ready(function () {
$("#btnSave").click(function () {
var model = {
testString: $("#txtArea").val(),
videoID: '#(Model.Video.iVideo_ID)',
taskID: document.getElementById('dropVal').value
};
$.ajax(
{
type: "POST", //HTTP POST Method
url: "/Video/Index", // Controller/View
data: JSON.stringify({ viewModel: model })
async: false,
processData: false,
contentType: false,
dataType: 'json'
}).success(function (json) {
$("#proever").html(json.responseText);
});
})
})
I am creating an asp.net application.
I have an image displayed inside the view of a controller action. When I click on an item in the view (say an image) I would like to pass some data (say ID) to a controller action.
I have the following code in the view:
#Url.Content("ActionName", "Controller");
I would like to send the data into the ActionName action of the Controller controller.
And the controller action looks as follows:
public ActionResult ActionName(string someParam)
{
return View();
}
I can call the controller action without a problem but I cannot pass the data. Thanks for help.
<a href='#Url.Action("MyAction", "MyController", new {id = "ID"})'>
<img src='#Url.Content("~/Content/Images/MyLinkImage.png")' />
</a>
You can Add image in URL action or create onclick function for image and make Ajax request
<a href="#Url.Action("ActionName", "Controller", new {someParam = "value"})">
<img />
</a>
you can make an ajax call
an example below
$('#btnSave').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/ControllerName/ActionName",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
$(element).closest("form").submit(); //<------------ submit form
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
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).
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.
I have a huger web form in my MVC app.
When I click my "save" button, the form is submitted and the values saved, and at the end I redirect to the same page/form.
But it re renders the whole form, when it was already loaded and there is no need.
How can I avoid that?
I want the SAVE button to behave like: save all but continue where I was.
My controller code:
[HttpPost]
[ValidateInput(false)]
public ActionResult FormCol(FormCollection collection)
{
...
if (Request.Form["DocumentId"] != null)
{
...
return RedirectToAction("FormCol", new { id = DocumentId });
}
View:
<input type="hidden" value="#document.Id" name="DocumentId" />
You will need to post your form via Ajax / jquery:
$.ajax({
url: '/someController/FormCol?variable1=' + $("#input1").val() + '&variable2=' + $("#input2").val(),
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data); //This is where you would do something based upon a successful save, such as alerting the user to their new document ID or something.
},
error: function () {
alert("error"); //This is where you know that your save failed.
}
});
And change your Controller action return Json:
public JsonResult FormCol(string variable1, string variable2)
{
//do saving stuff here
return Json(new { id = DocumentId });
}