ASP.NET MVC ajax - data transfer - asp.net-mvc

How can I get result from action?
I need to show the commentID on the page (aspx) after successes comment insert.
controller
[AcceptVerbs(HttpVerbs.Post )]
public ActionResult ShowArticleByAjax(Guid id, string commentBody)
{
Guid commentID = Comment.InsertComment(id, commentBody);
//How can I tranfer commentID to the aspx page ???
return PartialView("CommentDetails",Article.GetArticleByID(id));
}
ascx
<%using (Ajax.BeginForm("ShowArticleByAjax", new { id = Model.ID },
new AjaxOptions {
HttpMethod = "Post",
UpdateTargetId = "divCommentDetails",
OnSuccess = "successAddComment",
OnFailure = "failureAddComment",
OnBegin = "beginAddComment"
}))
{ %>
<p>
<%=Html.TextArea("commentBody", new { cols = "100%", rows = "10" })%>
</p>
<p>
<input name="submit" type="image" src="../../Content/Images/Design/button_s.gif"
id="submit" />
</p>
<%} %>
aspx
doesn't matter

Use the this:
ViewData["ID"] = commentID;
and then print it with:
<%= ViewData["ID"]%>

Related

Image upload using #Ajax.BeginForm in .NET MVC?

I want to upload image using Ajax.BeginForm in my application.
Currently HttpPostedFileBase file is getting value 0. Anyone Please guide me here.
I have tried this code but file is not uploading.
Appreciated, if anyone can provide some solutions for this. If I use #Html.BeginForm then It works but I want to use #Ajax.BeginForm.
Model
public class ClsUpload
{
public string FilePath { get; set; }
}
Controller
public ActionResult Edit(ClsUpload model,HttpPostedFileBase file)
{
if (Request.Files.Count > 0)
{
file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath("/Content/Images/"), fileName);
file.SaveAs(path);
model.FilePath = path;
}
}
try
{
UploadDetials details = new UploadDetials();
details.UpdateDetails(model);
return RedirectToAction("Index");
}
catch
{
return RedirectToAction("Index");
}
}
Partial View
#model XX.X.Models.File.ClsUpload
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "partial", InsertionMode = InsertionMode.Replace }))
{
#Html.HiddenFor(model => model.FilePath)
<input type="file" name="file" />
<img src=#Model.FilePath alt="Image" />
<input type="submit" value="Save" />
}
You can update your code with FormMethod.Post, new { enctype = "multipart/form-data" }) and [AcceptVerbs(HttpVerbs.Post)] as follow
In Partial View
#using (Html.BeginForm("ActionMethod1", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
In Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ActionMethod1(HttpPostedFileBase pic)
{
}
This is old, but I want to show how I have accomplished uploading a file using Ajax.BeginForm(). Basically, the overloads will tell you what is possible. I use the overload for: "string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes". Note: I use null for "routeValues".
Here is a code example:
#using (Ajax.BeginForm("UploadFile", "Home", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "MyIDToUpdate", OnSuccess = "EditSuccessClearForm('IDToClear', '')", OnFailure = String.Format("NewGenericFailure(xhr, '{0}')", "#IDToPassThisFunction"), InsertionMode = InsertionMode.ReplaceWith }, new { enctype = "multipart/form-data", #id = "NewFileFormID" }))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-sm-8 col-sm-offset-1">
#Html.TextBox("file", "", new { type = "file", accept = ".jpg, .jpeg, .png, .pdf", #id = fileID, onchange = VerifySizeOfFile })
</div>
<div class="col-sm-2">
<button type="submit" id="FileSubmitButton" class="btn btn-primary">Upload</button>
</div>
</div>
}

Retrieve partial view data

I have menu and using this I'm rendering partial view in my index page
#Ajax.ActionLink("week I", "firstWeekWinners", new
{
}, new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "weeWinnersDIv",
InsertionMode = InsertionMode.Replace
}, new { #class = "weekDays wactive" })
and there's partial view controller:
public PartialViewResult firstWeekWinners()
{
ViewBag.laptopWinners = db.firstWeekLaptopWinner().ToList();
ViewBag.tabWinners = db.firstWeekGalaxyWinner().ToList();
ViewBag.ipodWinners = db.firstWeekIpodWinner().ToList();
ViewBag.headPhonesWinners = db.firstWeekHeadPhonesWinner().ToList();
ViewBag.kingstonWinners = db.firstWeekkingstonUsbWinner().ToList();
return PartialView();
}
and partial view:
#if (ViewBag.laptopWinners != null)
{
<div class="winnersPrizeOverflow">
<div class="winnersPrizePic"></div>
<div class="winnersAllprizeLeft"><p>12</p></div>
</div>
foreach (var q in ViewBag.laptopWinners)
{
<span>#q.firstName</span>
<br />
<span>#q.lastName</span>
<br />
<span>#q.fbId</span>
<br />
<span>#q.sumOfBids</span>
<br />
}
}
If I'll click to this ajax.actionlink it renders this view but without this if I'll put #Html.Partial("firstWeekWinners") it doesn't goes in controller to retrieve my data.
How can I improve that?
To call your firstWeekWinners method use #Html.Action(), not #Html.Partial()
#Html.Action("firstWeekWinners")
Refer to the documentation for the various overloads, and these question/answers explaining the differences and usage.

MVC Session Not Showing in PartialView

I am doing a post back to a controller and setting Sessions. After they are set, it shows up in the first tab, but when I click next tab that loads another partialview, I do not see sessions set.
order.cshtml with Tabs...
<div id="tabs">
<ul class="nav nav-tabs">
<li>General</li>
<li>Item</li>
<li>Total</li>
</ul>
<div id="tabs-1">
#{Html.RenderPartial("_Partial_General_Tab", Model.GeneralTab);}
</div>
<div id="tabs-2">
#{Html.RenderPartial("_Partial_Item_Tab", Model.ItemTab);}
</div>
<div id="tabs-3">
Content for Tab 3 goes here.<br />
</div>
</div>
Tab 1
#model Mvc5.Models.ORDERMetadata
#{
var ordernumber = (int)Session["Order_Number"];
var princid_session = Session["PrincId"];
var custid_session = Session["CustId"];
}
OrderNumber: #ordernumber <br />
PrinicId: #princid_session <br />
CustID: #custid_session <br />
#using (Ajax.BeginForm("Edit", "Order",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "target"
}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
Enter model data here....
<button id="editorder" type="submit" class="btn btn-default">Save</button>
}
Tab 2
#model Mvc5.Models.ORDER_DETAILSMetadata
#{
var ordernumber = (int)Session["Order_Number"];
var princid_session = Session["PrincId"];
var custid_session = Session["CustId"];
}
OrderNumber: #ordernumber <br />
PrinicId: #princid_session <br />
CustID: #custid_session <br />
#using (Ajax.BeginForm("Items", "Order",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "target"
}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
Enter model data here....
<input type="submit" value="Add" class="btn btn-default" />
}
Edit Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ORDERMetadata model)
{
try
{
// update order
....
db.Entry(order).State = EntityState.Modified;
db.SaveChanges();
Session.Clear();
Session["Order_Number"] = model.Order_Number;
Session["PrincId"] = model.Princ_ID;
Session["CustId"] = model.Cust_ID;
return PartialView("_Partial_General_Tab", model);
}
catch (DbEntityValidationException ex)
{
return RedirectToAction("Index", "Error");
}
}

First day in AJAX in .NET MVC4, it doesn't work

Still trying to figure that out, here is my workflow:
once submit been clicked, the jquery will send a post request to call the method
method return a partial view
display on <div id = "messageForm">...</div> part
below is the form view:
//SignUp.cshtml:
<div id ="messageForm">
#using (Ajax.BeginForm("SignUp", "MVP", new AjaxOptions
{
Confirm = "Are you sure you want to send this message?",
HttpMethod = "Post",                                 
InsertionMode = InsertionMode.Replace,                                 
LoadingElementId = "loading",                                 
UpdateTargetId = "messageForm"
})) {
#Html.AntiForgeryToken();
#Html.ValidationSummary(true)
<fieldset>
<legend>
messageModel
</legend>
<p>
<input type ="submit" value ="Send Message" />
</p>
</fieldset>
here is the controller:
//MVPController
[HttpPost]
public ActionResult SignUp(MVCView model){
return PartialView("_ThankYou");
}
public ActionResult SignUp(){
return View();
}
Here is the partial view in view folder:
ThankYou.cshtml:
<h1>Thank you so much! We will contact you later</h1>
When testing it, I didn't see the confirm dialog and it redirect to the thank you page
Can anyone tell me why that happened?
You have:
#using (Ajax.BeginForm("ThankYou", "MVP", new AjaxOptions
I think this should be:
#using (Ajax.BeginForm("SignUp", "MVP", new AjaxOptions
The first string is the Action name, and you only have SignUp in the controller.

Update drop down using Ajax.ActionLink

I am trying to update the dropdown list:
View:
<div class="editor-field">
Names: <%: Html.DropDownList("names", (SelectList)ViewData["Names"]) %>
<%:Ajax.ActionLink("Refresh", "GetNames", new AjaxOptions { UpdateTargetId = "names", HttpMethod = "GET" })%>
</div>
Controller:
[HttpGet]
public ActionResult GetNames()
{
List<String> names = this.GenerateNames();
return Json(new SelectList(names));
}
The flow is the following: when user makes the first request, the list is updated from viewdata, then user presses refresh and the dropdown is populated usin ajax request.
I tried to return both JSON result - the dropdown is not updated. When returning SelectList the dropdown just gets cleared.
How can I accomplish this task?
You could put this drop down into a partial (Names.ascx):
<%# Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<YourApp.Models.SomeViewModel>" %>
Names: <%: Html.DropDownList(x => x.SelectedName, Model.Names) %>
And then in your main view use this editor template:
<div class="editor-field">
<span id="names"><% Html.RenderPartial("Names"); %></span>
<%: Ajax.ActionLink("Refresh", "Names",
new AjaxOptions { UpdateTargetId = "names", HttpMethod = "GET" }) %>
</div>
And you controller action could look like this:
public ActionResult Names()
{
var model = new SomeViewModel
{
// TODO: fetch the names from db:
Names = new SelectList(new[] {
new { Id = "1", Text = "name 1" },
new { Id = "2", Text = "name 2" },
new { Id = "3", Text = "name 3" },
}, "Id", "Text")
}
return View(model);
}
Just update the viewdata again so the view can use the same code to update itself for the second shot, being the Ajax return. And u don't need to use Json for that. Let me know how it goes.

Resources