Update List in ViewModel with Ajax ASP .NET MVC - c#

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);
});
})
})

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" });
}

How to display succes or error message in MVC with Javascript?

I'm wondering how to display a succes or error message on succes or fail by a controller action in my MVC project with bootstrap. For example I got the following action:
Input:
Javascript method to send data to controller:
//Sends data filled in in modal to backend.
$(document).ready(function () {
$("#btnSubmit").click(function () {
var datastring = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "/ApiBroker/AddApi",
dataType: 'json',
data: datastring,
});
$('#myModal').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
})
})
Controller method:
[HttpPost]
public ActionResult AddApi(ApiRedirect model)
{
var data = model;
try
{
List<ApiRedirect> list = dbProducts.ApiRedirects.ToList();
int companyID = dbProducts.Companies.Where(x => x.CompanyName == model.Company.CompanyName).FirstOrDefault().CompanyID;
int mappingID = dbProducts.MappingNames.Where(x => x.Name == model.MappingName.Name).FirstOrDefault().MappingID;
ApiRedirect api = new ApiRedirect();
api.ApiName = model.ApiName;
api.CompanyID = companyID;
api.ApiURL2 = model.ApiURL2;
api.MappingID = mappingID;
api.ResponseType = model.ResponseType;
dbProducts.ApiRedirects.Add(api);
dbProducts.SaveChanges();
return View ();
}
catch (Exception ex){
throw ex;
}
}
If the method AddUser added the user into my database I want to display a error message, and if the user was not added I want to display a error message. I dont know how to achieve this, any suggetions?
Thanks in advance!
UPDATE
So the alert works but the POST call is getting the following internal server error:
Firstly you ajax needs to be updated to use a success or failure
$.ajax({
type: 'POST',
url: "/ApiBroker/AddApi",
data: datastring,
dataType: 'json',
success:
function(data){
//... put your logic here
},
error:
function(){ alert('error'); }
});
Secondly you need to update your controller action to return a IHttpActionResult where you can specify a Response message.
If you look at this
HttpResponseMessage

How to call an Action method using ajax for a button click which is in partial view in MVC?

I'm new to MVC. I got a situation where I need to pass a parameter from view to controller on the button click (the button is in partial view), which then renders another partial view in the same page.
Steps followed:
I used jquery button click event for the button of partial view.
I made an ajax call to pass the parameters from my view to the controller.
The following is my code:
$(document).on("click", "#btninPartialView", function(e){
var data = $("txtinPartialView").val();
$("#mainPageContainer").load("/Controller/Action", data, function(){
$.ajax({
//url: #Url.Action("Action", "Controller"),
type: GET,
data: {
id: data
},
success: function(){
}
error: function(){
}
})
}
})
Problem:
The problem is that, the data I'm received in the action method is null.
Please let me know if I'm missing anything.
Thanks in advance.
$(document).on("click", "#btninPartialView", function(e){
var data = $("txtinPartialView").val();
$.ajax({
url: "/Controller/Action",
type: GET,
data: {
id: data
},
success: function(result){
$("#mainPageContainer").html(result);
}
error: function(){
})
})
This should work.
Please check with the arguments your Action method is accepting.
for example if signature is
public ActionResult Action1(string name)
then you need to pass the data as
var data = { name : $("txtinPartialView").val() }
The problem is that you are mixing both jquery ajax and load function, load function sends an ajax call behind the scenes, so you need to use one of them, not both, so try like:
$(document).on("click", "#btninPartialView", function(e){
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: GET,
data: {
id: $("txtinPartialView").val()
},
success: function(response){
$("#mainPageContainer").html(response);
},
error: function(){
}
});
});

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.

save data in session one by one and save them altogether in database

I am sending ajax request to save model in json format in a Session
<script type="text/javascript">
$(function () {
$('#addSubject').click(function () {
var mydata = {
"SubjectId": $('#subjectid').val(),
"ObtainedGpa": $('#obtainedgpa').val(),
"SubjectTypeId": $('#subjecttypeid').val()
};
var dataToPost = JSON.stringify(mydata);
$.ajax({
type: "Post",
url: "/PreviousExamInfo/SaveSubjectInfo",
contentType: "application/json;charset=utf-8",
data: dataToPost,
dataType: "json",
});
})
});
</script>
this is done successfully.But the in my action i have to save them in Session.The approach is like "Click The ADD button and save the Values in the Session, again click the ADD button and store the new values in session with the previously stored values".And after clicking the submit button all the values which is in the session will be stored in database. How can I know that the session works as I expecting?Because wher I use
var mySession=Session["myItem"]
this only shows the new values not what I was added previously.Should I use Session? Or Is there anything else that I can use?
[HttpPost]
public JsonResult SaveSubjectInfo(PreviousExamSubject previousExamSubject)
{
List<PreviousExamSubject> list=new List<PreviousExamSubject>();
list.Add(previousExamSubject);
Session["myitem"] = list;
return Json(JsonRequestBehavior.AllowGet);
}
The code always replaces the existing Session["myitem"] with a new list. To append instead you could do something like this:
[HttpPost]
public JsonResult SaveSubjectInfo(PreviousExamSubject previousExamSubject)
{
List<PreviousExamSubject> list= (List<PreviousExamSubject>) Session["myitem"] ?? new List<PreviousExamSubject>();
list.Add(previousExamSubject);
Session["myitem"] = list;
return Json(JsonRequestBehavior.AllowGet);
}

Categories

Resources