Rendering view in ASP.Net MVC - asp.net

In my code I am using a partial view (call it PV1)
<div id="div_1">
<% Html.Partial("PV1", Model); %>
</div>
and in that partial view I am using "Ajax.BeginForm" to redirect it to a particular action, hence it is doing so ...
using (Ajax.BeginForm("action1", "Forms", null, new AjaxOptions { UpdateTargetId = "div_1" }, new { id = "form1" }))
{
Response.write("I am here.");
}
public ActionResult action1(XYZ Model)
{
//
return PartialView("PV1", Model);
}
at the last line of action I am again calling the same partial 'PV1', hence it is doing this too ...
but when rendering the view it don't print or do the steps written with in partial view, it override them with and show nothing ...

Html.Partial actually returns the result of rendering the view, you want to do <%= Html.Partial() %> or <% Html.RenderPartial(); %>
Html.Partial() returns the Html and thusly must be output on the page via <%= %> and Html.RenderPartial() uses Response.Write to output onto the page and can be used with <% %>.

This is not what you would use Ajax.BeginForm for. That helper is used to create actual <form> tags that will later be submitted to the server using MVC's unobtrusive ajax (so you still need some kind of a trigger action - a button, javascript - anything that submits the form).
I'm am not very clear on what you're trying to achieve. If you want to load a partial view with ajax, I would suggest using something like jQuery's ajax load method.

Related

JavaScript action result no longer working after converting to partial view

Early yesterday, the following validation notice was working correctly. Then we converted the Index view where the request for this action originates to use a partial view, and the Delete ActionLink is now inside that partial view, and now the string argument to the JavaScript method call is rendered literally and as the only content on the 'destination' Delete view.
public ActionResult Delete(int id)
{
var perm = JobCardService.CheckBusinessRules(id);
if (!string.IsNullOrEmpty(perm))
{
return JavaScript("NotifyFailure('You may not delete this Installation: " + perm + "', false, 2000);");
}
JobCardViewData viewData = ViewDataFactory.CreateBaseViewData<JobCardViewData>("Installation List");
return View("Delete", viewData);
}
The Filter action returns the partial view, and is requested as below:
<div class="editor-field">
<% using (Ajax.BeginForm("Filter", "JobCard", new AjaxOptions { UpdateTargetId = "jobList" }))
{ %>
<%= Html.DropDownListFor(model => model.RequesterId, new SelectList(Model.RequesterList, "RequesterID", "CompanyName", Model.RequesterId), new { onchange = "$('#Select_Save').click();" })%>
<input id="Select_Save" type="submit" value="Save" style="display: none" />
<%
}%>
</div>
If the action method is responsible for returning a view, seems like the response shouldn't be returning a JavaScript if in error because no underlying ASP.NET page would be served, which means that you would see it as literal text.
Consider assigning the method call to ViewData, and in your client do something like:
<% if (ViewData["X"] != null) { %>
<script type="text/javascript">
<%= ViewData["X"] %>
</script>
<% } %>
Calling VIewData["X"] like I do should render the JavaScript code directly and get directly executed when parsed.
I think that might work; you can always utilize other mechanisms like eval to parse content, or do whatever else you might need....
Refer to the comment of this question ASP.NET MVC Javascript ActionResult
The other aspect is that using this return type is considered to be an anti-pattern and should be avoided. The suggested approach is to use a Json result.
Working example for JavaScriptResult in asp.net mvc
http://devlicio.us/blogs/billy_mccafferty/archive/2009/02/07/beware-of-asp-net-mvc-javascriptresult.aspx
Edit:
Since javascript is being returned from the Controller, an alternative would be to send script back to the browser that redirects the user to the correct page.
public ActionResult Delete(int id)
{
var perm = JobCardService.CheckBusinessRules(id);
if (!string.IsNullOrEmpty(perm))
{
return JavaScript("NotifyFailure('You may not delete this Installation: " + perm + "', false, 2000);");
}
// you may need to do a bit more to create a URL in the form of http://...
UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
string url = u.Action("ActionName","ControllerName", new{id=1}); // the new Action will return the delete view
return Javascript(String.Format("window.location =""{0}"",url);
}
Refer to Creating a URL in the controller .NET MVC for more on the UrlHelper.
This may not be the best way to do this, but every other answer I have come across has required extensive rework to achieve. This requires one small, simple change and works exactly as required. All I had to do was change the Delete action link from this:
<%= Html.ActionLink("Delete", "Delete", new { id = item.InstallationDBNumber }) %>
to this:
<%= Ajax.ActionLink("Delete", "Delete", new { id = item.InstallationDBNumber }, new AjaxOptions { HttpMethod = "Get" }) %>

Passing Data from Usercontrol to controller

I am new to MVC, and trying something and got stuck somewhere in between.
I have a user control there I have three textbox html type(ID, Lastname, firstname) and a submit buttom.
I set the button like
<input type="button" value="Search"
onclick="location.href='<%= Url.Action("action", "controller") %>'" />
I have called this usercontrol on some view through
<%= Html.Partial("ucName") %>
Now on pressing that button(on user control) I need to pass the data from these textboxes to controller again to some specific action(Http Post action). By using this data I want to do some database interaction and storing the result in a dataset and pass this data set to same view again to show up in some Grid.
I know the first part in conventional Asp.net can be done by raising the event through delegate but don't know how to do that in MVC.
In your actionresult you should have;
public ActionResult(MyModel model)
{
//now do something with model
}
Get rid of the button and use a submit button instead and then use BeginForm so that it will submit to the same action and controller.
MyModel should contain the three fields and your model should inherit from MyModel as well so that MVC knows where to get the data from.
Have you gone through the NerdDinner sample yet because it sounds like you haven't. you need to do that first to get an appreciation of how MVC models and view work.
Can't you simply use a submit button that will post data to the desired controller action:
<% using (Html.BeginForm("action", "controller", FormMethod.Post)) { %>
<!-- ... your textboxes here ... -->
<input type="submit" value="Search" />
<% } %>
You could also use FormMethod.Get if you want the parameters to be passed in the url.

render .ascx page into .aspx page using javascript, jquery

i have aspx page which has following js function which is called on button click
<input type="button" onclick="calltemp1()" value="Temp1"/>
<script type="text/javascript">
function calltemp1() {
$("#Renderthisdiv").load("/Views/Templates/_Temp1.ascx");
}
</script>
my _Temp1.ascx page renders another page Temp1.ascx
my _Temp1.ascx contains
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<div>
<%Html.RenderPartial("/Views/Templates/Temp1.ascx"); %>
</div>
when i run the program i get the JavaScript runtime error saying "object expected"
please help me to solve this issue
Your JavaScript call is going to make another trip through the MVC Pipeline. So it will hit routing, a controller, and then a view. Your JavaScript should not try to hit the ascx file directly, but a route that maps to a controller that renders the view.
Your JS should look like this (note this is using a root relative URL, you may have to adjust):
$("#Renderthisdiv").load("/template/temp1");
Alternately, you can use an HTML helper to get the URL, but the JS will have to be in your view:
$("#Renderthisdiv").load("<%= Html.Action("temp1", "template") %>");
That URL will hit the Temp1 action on the TemplateController
public class TemplateController : Controller {
public ViewResult Temp1() {
return View("Temp1");
}
}
Just add the appropriate action to your controller so you can use jQuery to render it:
public class TemplateController : Controller {
public ViewResult Temp1() {
return View("_Temp1")
}
}

asp.net mvc parameter

I want to display a prompt message when he is redirceted from a special page, how can accomplish this?
Passing messsage as paramater is not so pretty.
a used a booling paramater to determinig situation to display message.
Why not pass the boolean in ViewData (whether to display the message) based upon interrogating Request.ServerVariables["http_referer"] in your controller?
in controller
ViewData["DisplayMessage"] =
Request.ServerVariables["http_referer"] == "http://Special.com";
in view
<% if ((bool)ViewData["DisplayMessage"])){ %>
<div>YOUR MESSAGE</div>
<% } %>
Kindness,
Dan

asp.net mvc complex ajax updates

i'm wanted to perform some ajax calls in a certain way.
I have a page. In this page are 2 ViewUserControls, say control1 and control2.
control1 has a list of Ajax.ActionLinks that call control2 like this:
<%= Ajax.ActionLink(page.Name, "PageDetails", new { pageSysName = page.SysName }, new AjaxOptions { UpdateTargetId = "pageEdit" })%>
control2 has an Ajax form which updates fine. The Ajax.BeginForm method looks like this:
Ajax.BeginForm("SavePage", "Admin", new AjaxOptions { UpdateTargetId = "pageEditUpdated" })
When a user hits the Save button, it currently updates a div called pageEditUpdated with a basic Content("updated") return type from the Controller.
The part i'm stumped on is how to update control2 to reflect the new changes.
To sum it up, a Page has 2 controls. I'd like control2 to refresh itself and also update a div to notify the user that the update has been performed.
Have your SavePage method return a partial that reflects the updated form contents, including the update message. Have the update target be the "inner container" of the form.
<% Ajax.BeginForm("SavePage", "Admin", new AjaxOptions { UpdateTargetId = "innerForm" }) { %}
<div id="innerForm">
<% Html.RenderPartial( "EditPageContents" ) %>
</div>
<% } %>
Your save action should then return
updatedModel.UpdateMessage = "updated";
return PartialView( "EditPageContents", updateModel );
and your partial view should have
<% if (!string.IsNullOrEmpty( UpdateMesage )) { %>
<%= Html.Encode( UpdateMessage ) %>
<% } %>
Honestly, though, this would be a lot easier using jQuery to post the form via AJAX:
$(function() {
$('form').submit( function() {
$.post( $(this).attr('action'), $(this).serialize(), function(data) {
$('#updateMessage').html(data).show();
});
return false;
});
});
I have to second tvanfosson's comment (I'd vote for him, but my reputation apparently isn't high enough yet). At any rate, when I integrated Ajax functionality with my MVC site I found the Microsoft provided Ajax methods to be fairly clunky. So instead I switched to using the jQuery.form plugin (good examples here). I found it made things much easier to work with. I just created MVC user controls for the section of page I wanted to be ajax, and just reloaded that user control as neccessary.

Resources