call to function from the controller in index.html - ajax

In my mvc app I have combobox, I am trying to do the following: when the user choose some item that will call to some function from the controller.
Index.html:
#using (Ajax.BeginForm("dor", "Home", new AjaxOptions
{
HttpMethod = "Get",
//UpdateTargetId = "myPic",
InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace
}))
{
#Html.DropDownListFor(x => x.SelectedFileName, Model.Files, new { Name = "map", #class = "form-control", onchange = "CallChangefunc()" })
}
.
.
.
<script type="text/javascript">
function CallChangefunc() {
window.location.href = '#Url.Action("dor","Home")';
}
</script>
HomeVM:
public class HomeVM
{
public List<SelectListItem> Files { get; set; }
public string SelectedFileName { get; internal set; }
public List<string> DynamicAlgorithems { get; set; }
}
Homecontroller:
public void dor()
{
//some code
}
The problem: when the user choose some item from combobox it redirect me to blank page i.e to http://localhost:55354/Home/dor, but I only want to call the function named dor, not to go to blank page!.
what am I missing?
Related

window.location.href always redirect to a new page URL assigned to it. You should use jQuery.ajax() to call the action method when onchange method triggered and return desired result:
jQuery (inside $(document).ready())
$('#SelectedFileName').change(function() {
var selectedFileName = $(this).val();
$.ajax({
type: 'GET',
url: '#Url.Action("Dor", "Home")',
data: { fileName: selectedFileName },
success: function (result) {
// do something
}
});
});
Controller
[HttpGet]
public ActionResult Dor(string fileName)
{
// do something
}
Note: Make sure that action method argument has same name with assigned data passed from AJAX callback.

Related

Post Model to Controller in ajax

This is My ajax Code
$('#RolesSave').click(function () {
var sRow = JSON.parse(JSON.stringify($('#table').bootstrapTable('getSelections')));
var ID = JSON.stringify(sRow, ["ID"]);
var view = {
CompanyCode: $('#Company').val(),
RolesCode: $('#Roles').val(),
ID,
};
$.ajax({
method: "POST",
url: '#Url.Action("Save")',
data: $('#formData').serialize(),
success: function (data) {
alert(data + '!!!')
},
error: function () {
alert('ERROR')
}
})
})
This is My Controller
[HttpPost]
public IActionResult Save(RightsModel view)
{
return View();
}
and This My Model
public class RightsModel
{
public List<string> ID { get; set; }
public string Company { get; set; }
public string Roles { get; set; }
}
and this is my view
<form id="formData">
#Html.DropDownListFor(m => m.Company, Model.Company)
#Html.DropDownListFor(m => m.Roles, Model.Roles)
<button id="RolesSave" class="btn btn-primary btn-light" type="submit">存檔</button>
<table id="table"></table>
My problem is when I use the code $('#formData').serialize(). It can convert the data in View into Model normally.
But when I use JSON.serialize(view), It can't achieve the same goal.
Even if I add [FormBody] to the Action, I cannot get any relevant information.
Any suggestions?
JSON.serialize is not exists in js,we usually use JSON.stringify.And you need to make sure the model structure of view is the same with model RightsModel.And you need to add contentType:"application/json", to ajax since you want to pass json type data to action.Here is a demo:
js:
$('#RolesSave').click(function () {
var sRow = JSON.parse(JSON.stringify($('#table').bootstrapTable('getSelections')));
var ID = [];
sRow.forEach(function (item, index) {
ID.push(""+item.ID);
});
var view = {
Company: $('#Company').val(),
Roles: $('#Roles').val(),
ID: ID
};
$.ajax({
method: "POST",
url: '#Url.Action("Save")',
data: JSON.stringify(view),
contentType:"application/json",
success: function (data) {
alert(data + '!!!')
},
error: function () {
alert('ERROR')
}
})
})
action:
[HttpPost]
public IActionResult Save([FromBody]RightsModel view)
{
return View();
}
result:
I try yo use var ID = ["1", "2", "3"]; to test,and it can work.ID need to be type List<string>.

HttpPost with AJAX call help needed

what else do i need in my code please, I have this so far:
<script type="text/javascript">
function PostNewsComment(newsId) {
$.ajax({
url: "<%= Url.Action("AddCommentOnNews", "Home", new { area = "News" }) %>?newsId=" + newsId + "&newsComment=" + $("#textareaforreply").val(), success: function (data) {
$("#news-comment-content").html(data + $("#news-comment-content").html());
type: 'POST'
}
});
}
$("#textareaforreply").val("");
</script>
and
[HttpPost]
[NoCache]
public ActionResult AddCommentOnNews(int newsId, string newsComment)
{
if (!String.IsNullOrWhiteSpace(newsComment))
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
ZincService.NewsService.AddCommentOnNews(newsId, newsComment, currentUser.UserId);
Zinc.DataModels.News.NewsCommentsDataModel model = new DataModels.News.NewsCommentsDataModel();
var today = DateTime.UtcNow;
model.CommentDateAndTime = today;
model.NewsComment = newsComment;
model.Firstname = currentUser.Firstname;
model.Surname = currentUser.Surname;
model.UserId = CurrentUser.UserId;
return View("NewsComment", model);
}
return null;
}
<div class="actions-right">
<%: Html.Resource(Resources.Global.Button.Reply) %>
</div>
i have no idea how this works, because it is not working in FF???
and the other thing is i must not pass return null i must pass JSON false ???
any help please?
thanks
You should encode your request parameters. Right now you have concatenated them to the request with a strong concatenation which is a wrong approach. There's a property called data that allows you to pass parameters to an AJAX request and leave the proper url encoding to the framework:
function PostNewsComment(newsId) {
$.ajax({
url: '<%= Url.Action("AddCommentOnNews", "Home", new { area = "News" }) %>',
type: 'POST',
data: {
newsId: newsId,
newsComment: $('#textareaforreply').val()
},
success: function (data) {
$('#news-comment-content').html(data + $('#news-comment-content').html());
}
});
}
Also you haven't shown where and how you are calling this PostNewsComment function but if this happens on the click of a link or submit button make sure that you have canceled the default action by returning false, just like that:
$('#someLink').click(function() {
PostNewsComment('123');
return false;
});
and the other thing is i must not pass return null i must pass JSON false ???
You could have your controller action return a JsonResult in this case:
return Json(new { success = false });
and then inside your success callback you could test for this condition:
success: function (data) {
if (!data.success) {
// the server returned a Json result indicating a failure
alert('Oops something bad happened on the server');
} else {
// the server returned the view => we can go ahead and update our DOM
$('#news-comment-content').html(data + $('#news-comment-content').html());
}
}
Another thing you should probably be aware of is the presence of dangerous characters such as < or > in the comment text. To allow those characters I would recommend you build a view model and decorate the corresponding property with the [AllowHtml] attribute:
public class NewsViewModel
{
public int NewsId { get; set; }
[AllowHtml]
[Required]
public string NewsComment { get; set; }
}
Now your controller action will obviously take the view model as argument:
[HttpPost]
[NoCache]
public ActionResult AddCommentOnNews(NewsViewModel viewModel)
{
if (!ModelState.IsValid)
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
ZincService.NewsService.AddCommentOnNews(viewModel.NewsId, viewModel.NewsComment, currentUser.UserId);
var model = new DataModels.News.NewsCommentsDataModel();
var today = DateTime.UtcNow;
model.CommentDateAndTime = today;
model.NewsComment = newsComment;
model.Firstname = currentUser.Firstname;
model.Surname = currentUser.Surname;
model.UserId = CurrentUser.UserId;
return View("NewsComment", model);
}
return Json(new { success = false });
}

Serialize SelectListItem and binding

I have model
public class UploadOptionModel
{
public UploadOptionModel()
{
OutputFormat = outputFormatList.Select(i => new SelectListItem
{
Text = i,
Value = i
});
}
public string Email { get; set; }
public IEnumerable<SelectListItem> OutputFormat { get; set; }
}
and View
#model PC.Models.UploadOptionModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(p => p.Email)
#Html.DropDownList("OutputFormat", Model.OutputFormat)
}
I am trying to submit the form above using Ajax call and bind it to model
//Calling ValidateFile Action controller
$.ajax({
url: '#Url.Action("ValidateFile", "Converter")',
data: JSON.stringify({ file: fileName, formData: serializedForm }),
contentType: 'application/json',
type: 'POST',
success: function (response) {
if (response.result) {
} else {
RemoveFile(fileName);
}
}
});
function serializeForm() {
var data = $("form").serializeArray();
var formData = {};
for (var i = 0; i < data.length; i++) {
formData[data[i].name] = data[i].value;
}
return formData;
}
The ValidateFile action
[HttpPost]
public JsonResult ValidateFile(string file, UploadOptionModel formData)
{
}
The problem is that UploadOptionModel.OutputFormat is not binding. I can't read selected dropdown value. UploadOptionModel.Email field is bind successfully.
You should have another property in your Model class, where you bind the selected value of the dropdownlist.
So in your model add something like
public string OutputFormatSelected { get; set; }
And then use it in your view, this way:
#model PC.Models.UploadOptionModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(p => p.Email)
#Html.DropDownListFor( m => m.OutputFormatSelected, m.OutputFormat)
}
Your problem was that you wee binding both the list of elements and the result to the same property

MVC3 Ajax Get String and post it back

on MVC3 Page load i have a String in a Model which is should be the JSONObj.
private string CreateJSONObj(Model model)
{ return "{ name: 'test', Items: [{ test: 1 }, { test: 2 }]"; }
Model.jsonModel = CreateJSONObj(model);
Now i want to implement it in my page:
<script>var jsModel = eval('#Model.jsonModel');
var jsonModel = $.toJSON(jsModel);
$.ajax({
url: 'Page/SetJSON/',
type: "POST",
data: jsonModel,
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function () {
$('#test').html('Saved').fadeIn(),
},
error: function () {
$("#test").html("error"),
}
});</script>
But the Controller gets a null Object. If i write the jsonstring into the script everthing is fine.
Should i use eval? But var jsModel = eval('#Model.jsonModel'); has no effect. What is wrong? :-)
You don't need to use a CreateJSONObj method or a jsonModel property on your model. In order to use it in the view you could simply use the JavaScriptSerializer class which will convert the server side model object into a javascript object:
<script type="text/javascript">
var jsModel = #Html.Raw(new JavaScriptSerializer().Serialize(Model));
$.ajax({
url: '#Url.Action("SetJSON", "Page")',
type: 'POST',
data: JSON.stringify(jsModel),
contentType: 'application/json; charset=utf-8',
success: function () {
$('#test').html('Saved').fadeIn();
},
error: function () {
$('#test').html('error');
}
});
</script>
This will successfully send the model to the following controller action:
[HttpPost]
public ActionResult SetJSON(Model model)
{
...
}
where the Model class contains all the necessary information:
public class Model
{
public string Name { get; set; }
public IEnumerable<Item> Items { get; set; }
}
public class Item
{
public int Test { get; set; }
}
and the controller:
public class PageController: Controller
{
// Used to render the view
public class Index()
{
var model = new Model
{
Name = "Test",
Items = new[]
{
new Item { Test = 1 },
new Item { Test = 2 },
}
};
return View(model);
}
// Used to handle the AJAX POST request
[HttpPost]
public ActionResult SetJSON(Model model)
{
...
}
}

How to use ajax call to pass json data to controller and render a partial view as result?

I need to pass model object to controller, and from there to call service to generate data for the partial view. I am able to pass the json object to the main view, and I am able to generate the partial view. However, I am having difficulties to render the partial view in the main view after the call. If I don't pass object to controller, I am able to render the partial view.
My Main goal is: to pass json object and render partial view with the same ajax call.
Would appreciate help on this.
I apologize for the lengthy code here, but not sure how I could do it some other way.
The following code works, where I do not pass Json object via ajax call, and create department object in the controller:
main view code:
#model PartialViewDemo.Models.School
....
<body>
....
<div>
#Html.Partial("_MyPartialView", Model.Department )
</div>
....
<div id="divTest"></div>
<input type="button" value="Click" id="btnClick"/>
</body>
<script src="~/Content/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function() {
$('#btnClick').click(function(data) {
var dept = {
DepartmentName: "test Dept",
DepartmentRule: "test rule",
Comment:" test comment"
};
$.ajax({
url: '/home/ShowPartailView/',
success: function (result) {
$('#divTest').html(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
});
});
</script>
controller code:
public ActionResult Index()
{
var model = new School();
model.Department = GetDepartmentList(3);
return View(model);
}
public List<Department> GetDepartmentList(int counter)
{
var model = new List<Department>();
for (var i = 1; i <= counter; i++)
{
var data = new Department();
data.DepartmentName = "Dept " + i;
data.DepartmentRule = "Rule " + i;
data.Comment = "Comment " + i;
model.Add(data);
}
return model;
}
public PartialViewResult ShowPartailView()
{
Department dept = new Department()
{
DepartmentName = "test Dept",
DepartmentRule = "test rule",
Comment = "We Rock!"
};
PartialViewResult result = PartialView("_MySecondPartialView", dept);
return result;
}
Partial view code:
#model PartialViewDemo.Models.Department
<h2>_MyView from partial view using PartialView</h2>
#if (Model != null)
{
<div>
<table>
<thead>
....
</thead>
<tbody>
<tr>
<td>#Model.DepartmentName</td>
<td>#Model.DepartmentRule</td>
<td>#Model.Comment</td>
</tr>
</tbody>
</table>
</div>
}
Model:
public class Department
{
public string DepartmentName { get; set; }
public string DepartmentRule { get; set; }
public string Comment { get; set; }
}
public class School
{
public List<Department> Department { get; set; }
}
However, when I pass in Json object to ajax call with all other code stay the same, except the following changes, the partial view won't show with click event.
$.ajax({
url: '/home/ShowPartailView/',
data: JSON.stringify(dept),
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#divTest').html(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
with controller code:
public PartialViewResult ShowPartailView(Department dept)
{
PartialViewResult result = PartialView("_MySecondPartialView", dept);
return result;
}
In the second example where you pass the object, you have specified the
dataType: 'json',
ajax option but your controller method is returning a partial view so it needs to be
dataType: 'html',
Side note: You can omit the contentType option and just use data: dept,
If you have return partial view then try this to render partial view in Div or any other element.
$(document).ready(function () {
$.ajax({
url: '/YourContollerName/YourActionName',
type: "POST"
})
.success(function (result) {
$('.loadOnDivClass').empty();
$('.loadOnDivClass').html(result);
})
.error(function (status) {
alert(status);
})
});
If Contrller Action return like this
return PartialView("_PartialList",modelObj);

Resources