Retrieve partial view data - asp.net-mvc

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.

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>
}

Ajax.BeginForm return PartialView code does not update

I am doing a login logout functionality using Ajax partial. For this I have a View which checks if the user is logged in or not and shows login or logout form accordingly.
On submit it does a ajax request and logs in or out the user. after doing so in controller I return same partial view.
So expected behavior is on return partial view must again check for login status and refresh the view accordingly, but instead same form is loaded.
Partial View:
#model Models.LoginModel
#if (Member.MemberIsLoggedOn())
{
using (Ajax.BeginForm("LoginForm", "Account", null, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "login-form-update",
},new {
#class="loginform form"
}))
{
<div class="col-md-12 padding-zero">
<div class="row flt-right">
Hello #Context.User.Identity.Name, <input type="submit" name="logout" class="btn btn-default" value="Log Out" />
</div>
</div>
}
}
else
{
using (Ajax.BeginForm("LoginForm", "Account", null, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "login-form-update",
}, new {
#class = "loginform form"
}))
{
<div class="col-md-12 padding-zero">
<div class="row flt-right">
<div class="form-group col-md-5">
#Html.TextBoxFor(x => Model.Username, new { #class = "form-control", #placeholder = "Username" })
</div>
<div class="form-group col-md-5">
#Html.TextBoxFor(x => Model.Password, new { #class = "form-control", #placeholder = "Password", #type = "Password" })
</div>
<div class="form-group col-md-2 flt-right">
<input type="submit" name="login" class="btn btn-default" value="Go" />
</div>
</div>
</div>
}
}
Controller:
public class AccountController : Controller
{
[HttpPost]
public ActionResult LoginForm(LoginModel model)
{
if (!ModelState.IsValid)
{
//Do nothing
}
// Login
if (Membership.ValidateUser(model.Username, model.Password))
{
FormsAuthentication.SetAuthCookie(model.Username, false);
return PartialView("Header/LoginForm", new Models.LoginModel());
}
else
{
ModelState.AddModelError("Username", "Username is not valid");
//do nothing
}
}
public ActionResult Logout()
{
FormsAuthentication.SignOut();
Session.Clear();
return PartialView("Header/LoginForm", new Models.LoginModel());
}
}
Now my problem is login/logout happens properly, but changes do not reflect unless page is refreshed, which is i want to avoid by Ajax.BeginForm(),
update
If i click two times the view changes, but this is not a good user experience.
I think this might be due to cache problem. You need to use output cache attribute to disable the cache for that action method .
You can use something like this.
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
Also clear your ModelState before the return .
ModelState.Clear();
return PartialView(model);

Controller function called 2 times at the same time MVC 4

my controller is called twice at the same time, i don't know what's wrong with the code
Controller:
List<Item> lstItems = new List<Item>();
public ActionResult _SaveItem(ItemDetails model)
{
Item it = new Item();
it.ItemName = model.itemName;
it.ItemURL = model.itemUrl;
it.Notes = model.Notes;
it.Price = model.unitprice;
it.Quantity = model.quantity;
it.Size = model.Size;
it.Weight = model.weight;
it.CategoryID = model.CategoryID;
it.Color = model.color;
lstItems.Add(it);
return PartialView(it);
}
View:
#model CSP1225.Models.ItemDetails
#using (#Ajax.BeginForm("_SaveItem", "Order", new AjaxOptions { InsertionMode = InsertionMode.InsertAfter, UpdateTargetId="Items" }))
{
<div id="Items">
</div>
<div class="form-horizontal" style="padding-left:20px;" >
#Html.EditorForModel()
<input type="Submit" id="addItem" value="Add Item" name="addItem" />
</div>
}
any help please.. ??
Actually i included jquery.unobtrusive-ajax Twice , that's why the code called twice at the same time :)

How to display a model state error in case I am returning a partial view

I have the following action method for creating new network info:-
public ActionResult CreateVMNetwork(int vmid)
{
VMAssignIps vmips = new VMAssignIps()
{
TechnologyIP = new TechnologyIP() { TechnologyID = vmid},
IsTMSIPUnique = true,
IsTMSMACUnique = true
};
return PartialView("_CreateVMNetwork",vmips);
}
[HttpPost]
public ActionResult CreateVMNetwork(VMAssignIps vmip)
{
if (ModelState.IsValid)
{
try
{
repository.InsertOrUpdateVMIPs(vmip.TechnologyIP,User.Identity.Name);
repository.Save();
return PartialView("_networkrow",vmip);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Error occurred: " + ex.InnerException.Message);
}
}
return PartialView("_CreateVMNetwork", vmip);
}
And I have the following _CreateVMNetwork view:-
#model TMS.ViewModels.VMAssignIps
#using (Ajax.BeginForm("CreateVMNetwork", "VirtualMachine", new AjaxOptions
{
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "networktable",
LoadingElementId = "loadingimag",
HttpMethod= "POST"
}))
{
#Html.ValidationSummary(true)
#Html.HiddenFor(model=>model.TechnologyIP.TechnologyID)
#Html.Partial("_CreateOrEditVMNetwork", Model)
<input type="submit" value="Save" class="btn btn-primary"/>
}
and _CreateOrEditVMNetwork view:-
#model TMS.ViewModels.VMAssignIps
<div>
<span class="f">IP Address</span>
#Html.EditorFor(model => model.TechnologyIP.IPAddress)
#Html.ValidationMessageFor(model => model.TechnologyIP.IPAddress)
<input type="CheckBox" name="IsTMSIPUnique" value="true" #(Html.Raw(Model.IsTMSMACUnique ? "checked=\"checked\"" : "")) /> |
<span class="f"> MAC Address</span>
#Html.EditorFor(model => model.TechnologyIP.MACAddress)
#Html.ValidationMessageFor(model => model.TechnologyIP.MACAddress)
<input type="CheckBox" name="IsTMSMACUnique" value="true" #(Html.Raw(Model.IsTMSMACUnique ? "checked=\"checked\"" : "")) />
</div>
The problem I am facing is that in case there is a model state error when adding a new entity, a partial view will be displayed with the model state error as follow:-
So my question is , if there is a way to display the model state error with the partial view , without updating the table row “insert after” as I am doing currently?
Thanks
Given the age i'm guessing you have already found a solution to this,
But here is an example using InsertionMode.Replace, maybe it can help someone else.
Snipped from view
#using (Ajax.BeginForm("AddPerson", "Home", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "UpdateSection" }))
{
<div id="UpdateSection">
#Html.Partial("PersonModel", Model.Person)
</div>
<input type="submit" value="add" />
}
Snipped from the controller
if (!ModelState.IsValid)
{
return PartialView("AddPerson", Person);
}
just make sure the "jquery.unobtrusive-ajax.min.js" script is included (i'm not sure it is by default)

ASP.NET MVC ajax - data transfer

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"]%>

Resources