ASP.NET MVC 3 - How to execute code after leaving a View? - asp.net-mvc-3

I'm in some trouble here. I have a view in which a company can thumbs up or down users of our site. The users are listed in a table and a column has the little hand images for the company to vote for or against the user. I had programmed an ActionLink there, however, I don't want a postback to happen every time a company vote on a user.
I decided to fill a list with the user IDs the company votes on and then, when leaving the page, a filter would intercept the request, get the list and process the votes. In this post I was taught how to initialize Filter parameters when calling the Action, but as you can see, I need a way for the Filter to get the Lists when the user exits the View, not in an Action.
I wouldn't want to use code-behind because, paired with MVC, it is not a best practice, but postbacks are not an option either.
Here's what I have so far:
public ActionResult ListUsers()
{
// Create a List with user models and send it to a View,
// which generates a WebGrid
return View(userList);
}
public class PromoteUsersFilter : ActionFilterAttribute
{
public int[] UsersToPromote { get; set; }
public int[] UsersToScrewWith { get; set; }
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
//insert promoting logic here
}
}
I believe there is a simple way of doing it, since most websites have this funcionality. Can anyone guide me with this?

Why not use AJAX that calls into your controller methods? If you set up your json properly, it will still be deserialized into an object, too.
This is OK even in the MVC mindset as far as I know. If you need to persist your data, but not update the entire page it is the only way that I know. You can even swap out entire partial views using AJAX.
I think the common misconception here is that the View portion (of MVC) is not just one page, but actually made up of a number of views smashed into the one page. So, updating one of those views separately does not really break the pattern.

Definitely go for the AJAX solution:
It could look like this in your view:
<div>
<span class="cssUpvote" id="upvote"><span>
<span class="cssDownvote" id="downvote"></span>
</div>
with some Jquery
<script>
$(document).on('click', 'upvote', function (event) {
$.ajax({
type: 'POST',
url: '/Votes/Upvote',
data: { id: companyId }
});
});
$(document).on('click', 'downvote', function (event) {
$.ajax({
type: 'POST',
url: '/Votes/Downvote',
data: { id: companyId }
});
});
</script>
And then your actions on the Controller
[HttpPost]
public ActionResult Upvote(int id)
{
//Do something with the (company)id
return Json();
}
[HttpPost]
public ActionResult Downvote(int id)
{
//Do something with the (company)id
return Json();
}

Related

What to return after Ajax call asp.net

After ajax call is completed and the model is posted successfully to the controller, what should the controller return?
In my case, I just want to add an item to the wishlist and that's it, no redirect.
Controller can return a message or somethingelse for sure that your action did successful
This question you need to know two points, 1.What type can asp.net core return? 2.What type can ajax can receive.
First, Asp.net core can return the following types: Specific type, IActionResult, ActionResult<T>, Learn more details in this document.
Second, Ajax can send and receive information in various formats, including JSON, XML, HTML, and text files.
From your question, I think you want to recive the model from controller and add it to the wishlist in the view. So, In my opinion, You can directly return the specified model, Asp.net core will serialize models to Json Automatically. Then you can use it in your ajax success method.
simple demo:
<div class="text-center" id="Test">
<h1 class="display-4">Welcome</h1>
<p>Learn about building Web apps with ASP.NET Core.</p>
</div>
<button onclick="GetDetails(2)">submit</button>
#section Scripts{
<script>
function GetDetails(id){
var postData = {
'ProductId': id,
};
$.ajax({
type: "Post",
url: "/Home/privacy",
data: postData,
success: function (res) {
document.getElementById("Test").innerHTML = res["name"];
}
});
}
</script>
}
Controller
List<Student> students = new List<Student>()
{
new Student()
{
Id="1",
Name="Jack",
Country="USA"
},
new Student()
{
Id="2",
Name="Nacy",
Country="Uk"
},
new Student()
{
Id="3",
Name="Lily",
Country="Cn"
}
};
[HttpPost]
public Student Privacy(string ProductId)
{
var result = students.Where(x => x.Id == ProductId).FirstOrDefault();
return result;
}

asp.net mvc3 c# checkbox with NO binding to database

I`m using these checkboxes in my view:
<input type="checkbox" value="1" name="reglist" id="prueba2" />
<input type="checkbox" value="2" name="reglist" id="prueba3" />
I`m using entity framework and My viewModel table does not contain values for those checkbox.
I need to get the checkbox checked in the controller and keep the ones that were checked previously along requests without binding the chexboxes to classes.
Just so that we're speaking the same language, I typically refer to the things that I save in the database as the "model" and what I use as the model on the view as the "view model".
In that, I would have a model as such:
public class Person{
// properties
}
And then I would have a view model like so:
public class PersonViewModel{
public Person Person { get; set; }
public bool OtherNeededValue1 {get; set;}
public bool OtherNeededValue2 {get; set;}
}
Now, on your view, user PersonViewModel as the model. Then, in your controller, your action will look like this:
public ActionResult Create (PersonViewModel viewModel)
{
if (viewModel.OtherNeededValue1)
{
// do something
}
var p = new Person {
FirstName = viewModel.Person.FirstName
};
}
This way you don't cloud your model with unnecessary properties, but you can still take advantage of the rich binding of MVC.
Cheers.
You can make an AJAX call to your controller every time a checkbox is clicked.
Ajax Call
$(function () {
$(':checkbox').change(function () {
$.ajax({
url: '#Url.Action("CheckBoxStatus")',
type: 'POST',
data: { isChecked: $(this).is(':checked'),
id: $(this).val()
},
success: function (result) { }
});
});
});
this will send the status and the value of the checkbox to the controller and the you can store the info in whatever way like.
Controller Method
public void CheckBoxStatus(bool isChecked, int id)
{
// Do what you like here
}

How to pass the full Model from view to controller via jquery in a MVC c# application

I have a list of checkbox's and textbox's. I want to let the user add items to the list via a partial view modal popup.
After the user adds an item to the list, if any items on the original view have values in them, I want them preserved, and the page refreshed with the added items.
I want to send the full model back to the controller from the original view, I can then just add the new items to that model and pass the model back to the original page and have all my values preserved.
I could grab all the values and pass them via loops and such in javascript (very tedious), but I think the full model would be the easiest way.
I sawe a link from Laviak on a post from here..., but I can't get it to work.
it states....
If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.
In our app, we do this with an extension method:
public static class JsonExtensions
{
public static string ToJson(this Object obj)
{
return new JavaScriptSerializer().Serialize(obj);
}
}
On the view, we use it to render the model:
<script type="javascript">
var model = <%= Model.ToJson() %>
</script>
You can then pass the model variable into your $.ajax call.
Has anyone got this to work???
Thanks
Bill
you can do something like this:
<script type="text/javascript">
var dataViewModel = #Html.Raw(Json.Encode(Model)); //Make sure you send the proper model to your view
function MethodPost(param1, param2, etc...) {
dataviewModel.Param1 = param1; //Or load a value from jQuery
dataviewModel.Param2 = $("#param2").val();
}
//Pass it to a controller method
$.post("#Url.Action(MVC.Home.PostMethodInController())", { viewModel: JSON.stringify(dataViewModel)} , function(data) {
//Do something with the data returned.
}
</script>
In the controller you get your class/model using Json.Net which is available on nuget.
public virtual ActionResult Index()
{
return View(new MyModelToView());//Send at least an empty model
}
[HttpPost]
public virtual JsonResult PostMethodInController(string viewModel)
{
var entity = JsonConvert.DeserializeObject<MyObject>(viewModel);
//Do Something with your entity/class
return Json(entity, JsonRequestBehavior.AllowGet);
}
Hope this helps.

ASP.Net MVC 3 Drop Down List

I am developing an ASP.Net MVC 3 Web Application. One of my Razor Views contains a few Textboxes and a Drop Down List. When the User selects an option from the Drop Down List, I need a Partial View, or something like this, to appear below the Drop Down List preferable without a post back.
The thing is, it isn't as easy as a simply JQuery Hide and Show for the Partial View, when the User selects an option from the Drop Down List, I need their option to be sent to a method in the Controller, perform some logic based on this option, and then return some data to the Partial View.
I haven't really got much experience with AJAX, but I get the feeling this is the technology I need to use in order to fulfil my problem.
Has anyone ever had to code anything similar to what I have described above? And if so, is AJAX what I need to use?
Also, if anyone knows of any tutorials or code snipets I could look at to help, that would be greatly appreciated.
Thanks.
UPDATE
I have followed Ryan's answer, but unfortunately I am still having some problems. I have created the following JavaScript file which is then referenced in my View
$(document).ready(function () {
$("#myDDL").change(ChangeEventOfDDL);
function ChangeEventOfDDL(){
var dropDownValue = $('#myDDL').val();
//alert(dropDownValue);
$.ajax({ type: "GET",
url: '#Url.Action("SomePartialView","testAjax")',
data: {
id: dropDownValue
},
success: function(data) {
$('#someDivToLoadContentTo').html(data);
}
});
}
});
View
<select id="myDDL">
<option></option>
<option value="1">F1</option>
<option value="2">F2</option>
<option value="3">ST1</option>
<option value="4">ST2</option>
</select>
<div id="someDivToLoadContentTo">
</div>
My Controller then looks like this
public class testAjaxController : Controller
{
//
// GET: /testAjax/
LocumEntities context = new LocumEntities();
public ActionResult SomePartialView(int id)
{
var test = "Hello World";
return View(test);
}
}
However, my method 'SomePartialView' never gets hit. Does anyone know why?
Thanks.
Yes Ajax would be the easiest thing to use here. There are plenty of good Ajax tutorials around, just remember that what Ajax does is effectively a background POST, so you can do everything you would normally do with MVC, except within an existing page.
The way I would get this to work would be to have your code something like this:
public class SomeController{
public ActionResult SomePartialView(){
// Do some logic
return View("SomePartial");
}
}
Your Ajax would be something like:
function ChangeEventOfDDL(){
$.ajax({
url: '#Url.Action("SomePartialView","Some")',
success: function(data) {
$('#someDivToLoadContentTo').html(data);
}
});
}
I hope that helps at least a little bit.
Crucially with Ajax, you can add a data object to the function, which is passed as a querystring. This means you can send values from your page quite easily with ajax. Working with the above example, the Javascript would be:
function ChangeEventOfDDL(){
var dropDownValue = $('#ddl').val();
$.ajax({
url: '#Url.Action("SomePartialView","Some")',
data: {
id: dropDownValue
}
success: function(data) {
$('#someDivToLoadContentTo').html(data);
}
});
}
The Id value is linked with the parameters of the method in your MVC class:
public class SomeController{
public ActionResult SomePartialView(int id){
// Do some logic
var model = MakeModelWithSupplierId(id);
return View("SomePartial",model);
}
}
And there you have an interactive partial view that has been populated with the value from your drop down.
Since a controller can also return a partial view, you can do the following:
$('#idofyourdropdown').change(function () {
var theValue = $(this).val();
$.post('#Url.Action("Action","Controller")', {nameOfParameter: theValue, function(data) {
$('#divWhereYouWantToAttachData').html(data);
});
});
On the change event of your dropdown, send the selected value to your desired controller action, which will pass it to the partial view and return the rendered html. The html is received in the data var and can be attached to the dom, wherever you want it (see jQuery documentation for this).
This is a common use case.
What you need to do is
create a controller method that can take the parameters you need (read about MVC model binding before you do so)
write javascript that will harvest the data you want from your form and make a call to your new controller method and render the results below
In jQuery it goes something like this:
$("#yourDIV").load('/area/controller/method', { property1: 'asasd', property2: 'asdasdadfa'})
The second parameter of this call should be prepared based on the data you harvest from your form. (if you don't know how, then learn javascript)

How to save checkbox checked values in Database [duplicate]

I have a simple mvc project consisting of one table named Persons and that table has some attributes like name, age, surname and so on.
I Recently added an attribute to table which is type of bit in SQL and bool in C# and for me it represents some status. If it is ok I put that status to true or false.
In one controller I create an index view of my Persons in the database and I display the status as a checkbox. That is working ok. What I want to do is to change the status if I click on that checkbox instead of using an edit view for all of the atributes.
I just want to save checkbox value from my index view to database.
Some people advised me to create an action in my controller like so:
public ActionResult Save(int id, bool status){}
Where id is id of my person in db and status is a value of the checkbox I clicked.
So how do I call that function with jquery, ajax or javascript and send those params?
I am not so good with ajax and a little bit afraid of it :)
And one more thing I manage to show checkbox value corectly from my databse only in this way:
#Html.CheckBox("somename", item.Status)
<input name="somename" type="hidden" value="false"/>
Any help or advice or sending me to good direction is good!
You have several options. One way would be to place the checkboxes in a (normal) form and then use the jQuery Form plugin to Ajaxify the form:
#using(Html.BeginForm()) {
#Html.Checkbox(...)
}
<script type="text/javascript">
$(document).ready(function () {
$('form').ajaxForm({
success: Saved,
error: HandleError
});
});
function Error(response, status, err) {
// code to handle error here
}
function Saved(responseText, statusText, xhr, $form) {
// code to handle succes, if any
}
</script>
You could, of course, use an #Ajax.BeginForm as well, but this has the advantage of being easily downgradable. Just remove the jQuery form initialisation and you got yourself a regular form : )
Another possibility is to simply use an #Ajax.ActionLink. I wrote a blog post on how to deal with Ajax.ActionLink that I think will help you out.
The signature for your controller action on your question looks correct:
public ActionResult Save(int id, bool status){}
Another options is actually to create a Settings view model (call it what you will), and in there just have a bunch of bool properties to represent the checkboxes:
public class Settings
{
public bool Status { get; set; }
// more properties here
}
then you can bind your action to the Settings object:
public ActionResult Save(int id, Settings settings){}
This will come in handy in case you end up having multiple checkboxes to bind.

Resources