asp.net-mvc RenderPartial onclick - asp.net-mvc

Greetings,
I have an asp.net mvc application. I have some links that corresponds to clients names. When user clicks on this link I would like to show an information of clicked client and additionally a textarea where user shall be able to write some text (comment) about selected client. How can I achieve it?
EDIT
I've made something like:
<%=Html.ActionLink(operatorWhoAnswered.Operator.FirstName, "ShowSingleConverstationWithAnswerForm", "MyMessages", new { id = operatorWhoAnswered.Operator.ROWGUID }, new AjaxOptions() { UpdateTargetId = "ss" }) %>
and my controller action looks as follows:
public PartialViewResult ShowSingleConverstationWithAnswerForm(string id)
{
SingleConversationWithAnswerFormViewModel vm = new SingleConversationWithAnswerFormViewModel();
PartialViewResult viewResult = new PartialViewResult();
viewResult.ViewName = "SingleConverstationWithAnswerForm";
viewResult.ViewData = new ViewDataDictionary(vm);
return viewResult;
}
but view opens in a new page, instead of div with id="ss"
EDIT2
Solution found! I don't know why I have used Html.ActionLink. Ajax.ActionLink works fine!

Try something like this:
Create a div that should be rendered when the user clicks. Name is something lika blabla. Then where your link is you have something like
<%=Ajax.ActionLink("Click here", "Action", "Controller", new { id = "some test data passed in"}, new AjaxOptions() { UpdateTargetId = "blabla" })%>
And let that action return your view

Related

Create proper link from MVC5 Ajax.ActionLink

I have an mvc view that contains a table of data. I want to include a 'Remove' button in there so users can delete records. I'm having trouble generating the proper link to go to my Delete action. In order to delete i need two values from the table, not just an id.
<td>
#Ajax.ActionLink("Delete",
"DeleteWorkItem",
"Project/Work",
new { hId = #w.ProjectId, workId = #w.WorkId},
new AjaxOptions()
{
AllowCache = false,
HttpMethod = "DELETE",
Confirm = "Are you sure you want to delete this record?"
})
</td>
is what i have so far but when the link is clicked it creates a Get request to a url and appends the two parameters in the query string. How can i get those parameter values in the url instead of the query string. Also, I want to call the http delete method but no matter what i put in that options value i get a get
My WorkController
[HttpDelete]
public ActionResult DeleteWorkItem(int hId, int workId)
{
this.brWorkManager.Delete(forhealthId, workId);
return RedirectToAction("Details");
}
my route:
routes.MapRoute(
"WorkItemDelete",
"FHProject/Work/DeleteWorkItem",
new { controller = "Work", action = "DeleteWorkItem" },
new { httpMethod = new HttpMethodConstraint("DELETE") }
);

How to redirect from AREA's cshtml page to normal controller's ActionResult using #Url.Action?

How can I redirect to an ActionResult of a normal controller from .cshtml page of my Area's view?
I have a common login screen for normal/admin user.
So based on the usertype json result will return the user type.
So now I want to redirect a user based on the usertype.
If a user is normal user then I can redirect him using
"var redirectUrl = '#Url.Action("Index", "Home")';" and then "window.location.href = redirectUrl;"
Above code is working fine.
But what to do in following case?
If a user is an admin, then I want to redirect him to "Index" ActionResult of "HomeController" which is present in "Admin" area.
To redirect outside the area use a blank string for the area:
#Url.Action("Index", "Home", new { area = "" })
This will default you back to the HomeController outside of the area.
If I understand correctly, you just need some conditional logic on your link.
#{
var redirectUrl = Url.Action("Index", "Home", new { area = "" })
if (this.User.IsInRole("Administrator"))
{
redirectUrl = Url.Action("Index", "Home", new { area = "Admin" })
}
}
<script>
var redirectUrl = '#redirectUrl';
window.location.href = redirectUrl;
</script>
Although, a better alternative might be to make your own HTML helper extension method so you can reuse the logic elsewhere.
Finally below syntax worked for me.
var adminHomePageUrl = '#Url.Action("Index","Home", new { area = "Admin" })';

ASP.NET MVC - Execute controller action without redirecting

I am trying to execute an action on a controller without redirecting to the associated view for that action. For a good example of what I am trying to achieve take a look at the music.xbox.com website. When you add a song to a selected playlist from a popup menu - the page just shows a notification without any redirect or refresh. how is this possible?
What I have is the following:
I have a _playlistPopupMenu partial view that renders the list of playlists as follows:
_PlaylistPopupMenu
#model List<OneMusic.Models.GetPlaylists_Result>
#if (Model.Count > 0)
{
<li style="height:2px" class="divider"></li>
foreach (var item in Model)
{
<li style="height:30px">#Html.DisplayFor(p => item.Name)
#Html.ActionLink(item.Name, "AddSong", "Playlist", new { playlistId = #item.PlaylistId, songId = 1 }, "")
</li>
}
}
The PlaylistController AddSong action is as follows:
public PartialViewResult AddSong(int? playlistId, int? songId)
{
if (ModelState.IsValid)
{
db.AddSongToPlaylist(playlistId, songId);
db.SaveChanges();
return PartialView("_AddToPlaylist", "");
}
return PartialView("_AddToPlaylist", "");
}
I am struggling with what to put in the _AddToPlaylist partial view which I think I need to be able to display a notification of some kind (Possiblly using PNotify add in for Bootstrap). MVC wants to always redirect to ../Playlist/AddSong?playlistId=1&songId=1
Any ideas on how to complete this last part of the problem would be great.
If you don't want "full page reloads" then you need to approach the problem slightly differently, using javascript to alter the page dynamically. A library such as JQuery might make manipulating the DOM a little easier.
Display the popup dynamically using javascript.
When the user hits OK/Submit on the popup, post the data back to the server using javascript, and have the controller you are posting to return some HTML.
Append the returned HTML block (partial view) to an existing div containing playlist tracks.
The most difficult part of this is the asynchronous post. Help with updating a div without reloading the whole page can be found in this question.
EDIT - Example
If you have a controller action (accepting POSTs) with the URL myapp.com/PlayList/AddSong/, then you'd set up JQuery to post to this URL. You'd also set up the data property with any form data which you'd like to post, in your case you'd add playistId and songId to the data property.
You'd then use the result of the AJAX query (HTML) and append it to the existing playlist HTML on the page. So assuming that you want to append the partial view's HTML to a div with ID playlistDiv, and assuming that your partial view returns HTML which is valid when appended to the existing playlist, then your javascript will look something like this:
var data = { playlistId: 1, songId: 1 };
$.ajax({
type: "POST",
url: 'http://myapp.com/PlayList/AddSong/',
data: data,
success: function(resultData) {
// take the result data and update the div
$("#playlistDiv").append(resultData.html)
},
dataType: dataType
});
Disclaimer: I can't guarantee that this code will work 100% (unless I write the program myself). There may be differences in the version of JQuery that you use, etc, but with a little tweaking it should achieve the desired result.
using System.Web.Mvc;
using System.Web.Mvc.Html;
public ActionResult Index()
{
HtmlHelper helper = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView(ControllerContext, "Index"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage());
helper.RenderAction("Index2");
return View();
}
public ActionResult Index2(/*your arg*/)
{
//your code
return new EmptyResult();
}
in your controller you must add bottom code:
public ActionResult Index(string msg)
{
if (Request.Url.ToString().Contains("yourNewExampleUrlWithOutRedirect.com"))
{
string html = "";
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.Encoding = Encoding.UTF8;
html = client.DownloadString("https://NewExampleUrl.com/first/index?id=1");
}
Response.Write(html);
}
...
}
your view must be empty so you add bottom code
#{
ViewBag.Title = "sample title";
if (Request.Url.ToString().Contains("yourNewExampleUrlWithOutRedirect.com"))
{
Layout = null;
}else
{
Layout ="~/Views/Shared/_Layout.cshtml"
}
}
#if (Request.Url.ToString().Contains("yourNewExampleUrlWithOutRedirect.com")==false)
{
before view like :
<div>hello world</div>
}

How to update parent view after submitting a form through a partial view?

I have a view which when a teacher is logged in lists the complete details of a student , it also lists the tasks given to the student by the teacher logged in. If the teacher wants to create a new task for the student he clicks the create new link which in turns make an Ajax call to the controller:
#Ajax.ActionLink("Create", "CreateTask", "Task", new { id = Model.StudentId },
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "create-div"
}, new { #class = "btn btn-default" })
which returns a partial view
[HttpGet]
public ActionResult CreateTask(int ?id)
{
//........
return PartialView("PartialViews/Task/_CreateTaskPartial");
}
In the partial view I am using Ajax.BeginForm to submit the data to create the actual task as follows
#using (Ajax.BeginForm("CreateTask", "Task",new AjaxOptions { UpdateTargetId = "create-div", InsertionMode = InsertionMode.Replace }))
{
// Form data
}
and finally in the CreateTask controller I create the task
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="TaskId")] Task #task)
{
if (ModelState.IsValid)
{
db.Tasks.Add(#task);
db.SaveChanges();
// If everything is successfull return empty
return new EmptyResult();
}
// If model errors send the view back
return PartialView("PartialViews/Task/_CreateTaskPartial", #task);
}
It creates the new task successfully but it does not update the main view which lists the details of a student and a list of created tasks. I have to refresh the page to see the last task added.
How can I make it possible so that when a 6th task is added via partial view, on success it updates the parent view and lists the 6th task also ?
I am not very experienced in MVC so please correct me where am I doing wrong.
I solved it, I got help from Here to solve it.
So what I did is instead of returning an EmptyResult() when the task is created I returned a JSON object
if (ModelState.IsValid)
{
db.Tasks.Add(#task);
db.SaveChanges();
// If everything is successfull return empty
//return new EmptyResult();
return Json(new { ok = true, url = Url.Action("Details","Student",new{id=#event.StudentId}) });
}
An d in the partial view which submits the form to vreate the task I added OnSuccess parameter in the AjaxOptions in the Ajax.BeginForm which calls a javascript function.
#using (Ajax.BeginForm("CreateTask", "Task",new AjaxOptions { UpdateTargetId = "create-div", InsertionMode = InsertionMode.Replace,OnSuccess = "onSuccess" }))
{
// Form data
}
And finally in the "onSuccess" function I cheked if the result is ok then redirect to the url in the result given by the controller.
var onSuccess = function doIt(result) {
if (result.ok) {
window.location.href = result.url;
}
};

Why Asp.net partial view not returning back?

I am a newbie and just started learning the asp.net mvc, as I was going through the partial view tutorial and I created the small test application which is working fine.
I have a page which has a customers order and each item has an edit buttons for adding or deleting the items and by pressing it I can increase an item or delete an item from the cart. And for such action I am using
HTML.actionlink("+", "AddToCart", "Orders", new { orderid=tempcart.orderid },
new AjaxOptions()
{
OnBegin = "showplaces",
OnSuccess = "hideloader"
}, null);
so when I click the button it goes to AddToCart() action and update the table in database but it doesn't update the partial view and the loader.gif stays forever on the page and don't call the hideloader() function.
Can you please tell me what's the problem?
1- First user Ajax.ActionLink as you are updating the partial view
2- One thing also place the cart's div id so it can get updated when action finishes.
3- And I had such problem once, so I did the following:
add OnFailure attribute in Ht
Ajax.ActionLink("+", "AddToCart", "Orders", new { orderid=tempcart.orderid },
new AjaxOptions()
{
UpdateTargetId = "cart_divId",
OnBegin = "showplaces",
OnFailure = "ShowDOMExcep",
OnSuccess = "hideloader"
}, null);
and use this method to get DOM exception:
function ShowDOMExcep(context) {
var html = context.get_data();
var placeholder = context.get_updateTarget();
$(placeholder).html(html);
return false;
}
hope this helps ...

Resources