how to use ajax.beginform with foreach and model to create button for each li inside a partialview ul list? (the buttons are there to remove items/li) - ajax

I am creating an mvc project and in it I am using foreachinside a partial view to fill an ul list in the view . My foreach collection is a list of model and I want to create a button for each model/li element that submits the current model to a PartialViewResult which then will delete the model from databse. So I try something like this:
#model WebApplication6.Models.Lang_User
#{ WebApplication6.Models.Entities db = new WebApplication6.Models.Entities();
List<WebApplication6.Models.Lang_User> langlist=db.Lang_User.Where(x => x.UserID ==Model.UserID).ToList();
}
{
#foreach (WebApplication6.Models.Lang_User item in langlist)
{using (Ajax.BeginForm("DilSil", new AjaxOptions())) {
<li id="#item.ID" class="list-group-item">#item.Languages.Language <button type="submit" class="btn btn-warning"></button></li>
}
}
But now i need to make something inside ajaxforms. When i submit one of the forms in ul list. It must submit the #item so is there a way to do it?
edit1: Delete PartialViewResult
public PartialViewResult DilSil(Lang_User dil)
{
db.Lang_User.Remove(dil);
db.SaveChanges();
System.Threading.Thread.Sleep(3000);
return PartialView("_DilPartial", dil);
}

All you need to do is, to send the unique Id of the entity in the form post. To do that, Keep the id in an input field, which is hidden inside the form. The input element name should match with your parameter name. When user clicks on the button, the form data will be submitted, including the hidden input
using (Ajax.BeginForm("DilSil", new AjaxOptions() { }))
{
<li id="#item.ID" class="list-group-item">
This is #item.ID
<input type="hidden" value="#item.ID" name="id" />
<button type="submit" class="btn btn-warning">Delete</button>
</li>
}
Now in your action method, read the id, get the entity and delete it. You can probably return the list of current data (read it again from db) and pass that and update the UI using UpdateTargetId and InsertionMode attributes or return a JSON response which you can handle in your OnSuccess handler
In your case, your li item id is same is the id of the entity .So you can return that information back to the client and the OnSuccess handler method can delete that element from the DOM
[HttpPost]
public ActionResult DilSil(int id)
{
var dil=db.Lang_User.Find(id);
db.Lang_User.Remove(dil);
db.SaveChanges();
return Json(new { status = "success" , id=id });
}
Now add an OnSuccess handler to your AjaxOptions when using Ajax.BeginForm helper method to render the form. This will be a javascript function which will be called after the ajax call is done. The response from server will be passed to this function.
using (Ajax.BeginForm("DilSil", new AjaxOptions() { OnSuccess = "DeleteDone" }))
{
<li id="#item.ID" class="list-group-item">
This is #item.ID
<input type="hidden" value="#item.ID" name="id" />
<button type="submit" class="btn btn-warning">Delete</button>
</li>
}
Now define the javascript method which reads the json response and delete the li item
function DeleteDone(a, b, c) {
if (a.status === 'success') {
$("#" + a.id).remove();
}
}

Related

partial views to get data and then post the results to save in database

I am very new to MVC, let me try to explain my scenario in plain simple English:
I have an strongly typed mvc form/page (Product.cshtml) with a model, say ProductViewModel.
This page has got two search buttons, one to search and bring the items to be added to the Product and other to bring in the location, most probably partial views.
Now, what I want is that these search results work in ajax form without complete post back, and then the results of these searches (items and location) should be posted back using model binding to the form when user clicks on the submit button.
What could be the best way of achieving this functionality?
Immediate responses will be well appreciated.
I thought, its good to share the complete code for clarity:
I have one form(Service1.chtml) that has a partial view to display users(_TestUser a partial view:read only), then another partial view(_PlotServiceRequestData) that should have a field to search the plot and bring back the details lke its owner name and landuser etc.
Then when I click on submit button of the main form, I should be able to read all data(main form) + new data from _PlotServiceRequestData partial view and save all data to database.
I was trying one more option, that is, to use #Ajax.ActionLink on Service1.cshtml to call the _GetPlotDetails method and then store partial view data in TempData, so that it is available to the form when users clicks on "Submit" button of Service1.cshtml, is this a right approach?, if I use ajax.BeginForm inside partial view then the data is posted to the
Service1 controller method which is actually to save the form data and not to update the partialview and in this method even I am not getting model data of the partial view.
Sevice1.cshtml:
#model ViewModels.TestViewModel
#{
ViewBag.Title =
"Service1";
}
#
using (Html.BeginForm())
{
#Html.LabelFor(m => m.Title)
#Html.EditorFor(m => m.Title)
#Html.Partial(
"_TestUser", Model)
<div id="RequestPlotData">
#Html.Partial(
"_PlotServiceRequestData", Model.requestData)
</div>
<button type="submit">Save Form</button>
}
#section Scripts {
}
_PlotServiceRequestData.cshtml:
===============================
#model ViewModels.PlotServicesRequestDataViewModel
<
div id="RequestPlotData">
#
using (Ajax.BeginForm("_GetPlotDetails", "Test", new AjaxOptions { UpdateTargetId = "RequestPlotData", Url = Url.Action("_GetPlotDetails","Test") }))
{
<h1>Request Details</h1>
 
<div>
#Html.LabelFor(m => m.plotAddress)
#Html.EditorFor(m => m.plotAddress)
<input type="submit" name="submit" value="Ajax Post" />
</div>
<div>
#Html.LabelFor(m => m.LandUser)
#Html.EditorFor(m => m.LandUser)
</div>
<div>
#Html.LabelFor(m => m.OwnerName)
#Html.EditorFor(m => m.OwnerName)
</div>
}
</
div>
CONTROLLER:
==========
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Mvc;
namespace
TestNameSpace
{
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Service1()
{
Injazat.AM.mServices.
LocalDBEntities context = new Injazat.AM.mServices.LocalDBEntities();
TestViewModel model =
new TestViewModel() { user = context.Users.First(), Title = "Land Setting Out",
requestData =
new PlotServicesRequestDataViewModel() { ServiceNumber ="122345", TransactionDate="10/10/2033" } };
return View(model);
}
[
HttpPost()]
public ActionResult Service1(TestViewModel model)
{
PlotServicesRequestDataViewModel s = (PlotServicesRequestDataViewModel)TempData[
"Data"];
TestViewModel vm =
new TestViewModel() { user = model.user, requestData = s, Title = model.Title };
return View(vm);
 
}
[
HttpGet()]
//public PartialViewResult _GetPlotDetails(string add)
public PartialViewResult _GetPlotDetails(PlotServicesRequestDataViewModel requestData)
{
//PlotServicesRequestDataViewModel requestData = new PlotServicesRequestDataViewModel() { plotAddress = add};
requestData.OwnerName =
"owner";
requestData.LandUser =
"landuser";
TempData[
"Data"] = requestData;
return PartialView("_PlotServiceRequestData", requestData);
}
}
}
You can probably use the jQuery Form plugin for this. This makes the process of posting the data from your form back to the server very easy. The form would post to an action that would return a partial view that you can then push into your UI.
To make this easier, jQuery form actually has a "target" option where it will automatically update with the server response (ie. the partial view returned from your search action).
View
<form id="searchForm" action="#(Url.Action("Search"))" method="POST">
<input name="query" type="text" /> <!-- order use Html.TextBoxFor() here -->
<input type="submit" />
</form>
<div id="result"><!--result here--></div>
Javascript
$('#searchForm').ajaxForm({
target: '#result'
});
Controller
public ActionResult Search(string query)
{
// Do something with query
var model = GetSearchResults(query);
return Partial("SearchResults", model)
}
This should hopefully help you to get on the right track. jQuery Form is a good plugin and is the main thing you should look into for ajaxifying your form posts back to the server. You might also want to look into using jQuery's $.post and $.ajax functions, but these require slightly more work.

Asp.net MVC, 4.0 - Ajax, field value is overriden after update

I am playing around with some ajax, and have experienced a very odd and to me illogical bug.
I am displaying a list of events, wrapped in a form, in a table. Each event has a unique ID (EventID). This is submitted to the action when a button is pressed.
A div surrounding the table is now updated with the partialview that the action has returned.
The problem
When the view is reloaded, all the HiddenFields that contains the field EventID, now cointains the same EventID as. the one that was submitted to the action
I have tried placing a breakpoint in the view, to see what value is put in the HiddenField. Here is see that the correct id is actually set to the field. but when the page updates, all the hiddenfields contains the same eventid as the one originally submitted to the action.
The partialview: _Events
#model SeedSimple.Models.ViewModelTest
<table class="table table-striped table-bordered table-condensed">
#foreach (var item in Model.events)
{
#using (Ajax.BeginForm("AddAttendantToEvent", "MadklubEvents", new AjaxOptions()
{
HttpMethod = "post",
UpdateTargetId = "tableevents"
}))
{
#Html.Hidden("EventID", item.MadklubEventID);
<input type="submit" value="Join!" id="join" class="btn" />
}
#using (Ajax.BeginForm("RemoveAttendantFromEvent", "MadklubEvents", new AjaxOptions()
{
HttpMethod = "post",
UpdateTargetId = "tableevents"
}))
{
#Html.Hidden("EventID", item.MadklubEventID);
<input type="submit" value="Leave" class="btn" />
}
}
</table>
AddAttendantToEvent Action:
[HttpPost]
[Authorize]
public ActionResult AddAttendantToEvent(int EventID)
{
if (ModelState.IsValid)
{
var uow = new RsvpUnitofWork();
var currentUser = WebSecurity.CurrentUserName;
var Event = uow.EventRepo.Find(EventID);
var user = uow.UserRepo.All.SingleOrDefault(u => u.Profile.UserName.Equals(currentUser));
user.Events.Add(Event);
Event.Attendants.Add(user);
uow.Save();
ViewModelTest viewmodel = new ViewModelTest();
viewmodel.events = madklubeventRepository.AllIncluding(madklubevent => madklubevent.Attendants).Take(10);
viewmodel.users = kitchenuserRepository.All;
return PartialView("_Events", viewmodel);
}
else
{
return View();
}
}
How all the input fields look after having submitted EventID 4 to the action
<input id="EventID" name="EventID" type="hidden" value="4">
I am suspecting, this is due to some side-effects from the ajax call, that i am unknown to.
Any enlightentment on the subject would be much appreciated :)

How to use ajax link instead of submit button for form?

I have Ajax Form in my view:
#using (Ajax.BeginForm("SearchHuman", "Search", new AjaxOptions(){
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "result" }))
{
<div class="editor-field">
#DescriptionStrings.Lastname:
#Html.TextBox("LastName")
</div>
<div class="editor-field">
#DescriptionStrings.Firstname:
#Html.TextBox("Name")
</div>
//submit button
<input type="submit" value='Start Searching' />
//submit link
#Ajax.ActionLink("search", "OtherSearch", new{lastName ="",...}, new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "tab"
})
}
I want to have submit button and the link for 2 different searches (in different databases) using only one form. But how to pass route values from the textboxes of the form into Ajax.ActionLink?
Thanks in advance!
But how to pass route values from the textboxes of the form into Ajax.ActionLink?
You can't. You should use a submit button if you want to send the values to the server. You could have 2 submit buttons in the same form which both submit to the same controller action. Then inside this action you can test which button was clicked and based on its value perform one or the other search.
Example:
<button type="submit" name="btn" value="search1">Start Searching</button>
<button type="submit" name="btn" value="search2">Some other search</button>
and then inside your controller action:
[HttpPost]
public ActionResult SomeAction(string btn, MyViewModel model)
{
if (btn == "search1")
{
// the first search button was clicked
}
else if (btn == "search2")
{
// the second search button was clicked
}
...
}
The solution we opted for was to implement a custom ActionMethodSelectorAttribute which allowed us to differentiate which button was pressed based on its name property. We then decorated many methods with the ActionName decorator giving them all the same action name (the one specified in the BeginFrom helper), and then we used our custom ActionMethodSelector decorator to differentiate which method is to be called based on the name of the button clicked. The net result is that each submit button leads to a separate method being called.
Some code to illustrate:
In controller:
[ActionName("RequestSubmit")]
[MyctionSelector(name = "Btn_First")]
public ActionResult FirstMethod(MyModel modelToAdd)
{
//Do whatever FirstMethod is supposed to do here
}
[ActionName("RequestSubmit")]
[MyctionSelector(name = "Btn_Second")]
public ActionResult SecondMethod(MyModel modelToAdd)
{
//Do whatever SecondMethod is supposed to do here
}
In view:
#using (Ajax.BeginForm("RequestSubmit",.....
<input type="submit" id="Btn_First" name="Btn_First" value="First"/>
<input type="submit" id="Btn_Second" name="Btn_Second" value="Second"/>
As for the custom attribute:
public string name { get; set; }
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
var btnName = controllerContext.Controller.ValueProvider.GetValue(name);
return btnName != null;
}

passing data from view to controller on asp.net mvc 3

i have problem to pass data from view to controller , i have view that is strongly typed with my viewmodel "TimeLineModel", in the first i passed to this view my viewmodel from action on my controller
public ActionResult confirmation(long socialbuzzCompaignId)
{
return View(new TimeLineModel() { socialBuzzCompaignId = socialbuzzCompaignId, BuzzMessages = model });
}
with this i can get info from my action and display it on view , but i have other action POST which i won't get my view model to do some traitement
[HttpPost]
public ActionResult confirmation(TimeLineModel model)
{
}
i can get some propretie of the model but in others no , for example i can get the properti "socialBuzzCompaignId" of model , but other propertie like "IEnumerable BuzzMessages" i can't get it , i dont now why !!
this is the content of my view
#model Maya.Web.Models.TimeLineModel
#{
ViewBag.Title = "confirmation";
}
#using (Html.BeginForm())
{
<h2>confirmation</h2>
<fieldset>
#foreach (var msg in Model.BuzzMessages)
{
<div class="editor-label">
#msg.LongMessage
</div>
<br />
}
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
You need to include BuzzMessages properties within a form element. Since it's not editable, you'd probably want to use hiddens. There are two ways to do this. Easiest is instead of doing a foreach loop, do a for loop and insert them by index.
#for (int i =0; i<Model.BuzzMessages.Count(); i++v)
{
<div class="editor-label">
#Model.BuzzMessages[i].LongMessage
#Html.HiddenFor(m => m.BuzzMessages[i].LongMessage);
</div>
<br />
}
but to do this you'd need to use an IList instead of an IEnumerable in your view model to access by index.
Alternatively, you could create an Editor Template named after your BuzzMessages class (whatever its name is).
#model BuzzMessagesClass
#Html.HiddenFor(m => m.LongMessages)
<!-- Include other properties here if any -->
and then in your main page
#Html.EditorFor(m => m.BuzzMessages)
Check out http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/ or search stack overflow if the details of editor templates confuse you.
Just like any HTML POST method, you have to get the data back to the Controller somehow. Just simply "showing" the data on the page doesn't rebind it.
You have to put the data in an input (or a control that will post back) to the appropriate model property name.
So, if you have a model property with name FirstName and you want this data to be rebound to the model on POST, you have to supply it back to the model by placing an "input hidden" (or similar control that postbacks) with the ID of FirstName will rebind that property to the model on POST.
Hope that explains it.
#foreach (var msg in Model.BuzzMessages)
{
<div class="editor-label">
#msg.LongMessage
<input type="hidden" name="BuzzMessages.LongMessage" value="#msg.LongMessage" />
</div>
}
It will post array of LongMessages. Get values like this:
[HttpPost]
public ActionResult confirmation(TimeLineModel model, FormCollection collection)
{
var longMessages = collection["BuzzMessages.LongMessage"];
}

Using two button in a form calling different actions

I have a form on my page:
#using(Html.BeginForm("DoReservation","Reservation"))
{
...some inputs
<button id="recalculate">Recalculate price</button>
<button id="submit">Submit</button>
}
When I click the "Recalculate price" button I want the following action to be invoked:
public ActionResult Recalculate(FormCollection form)
{
var price = RecalculatePrice(form);
... do some price recalculation based on the inputs
return PartialView("PriceRecalculation",price);
}
When I click the "Submit" button I want the "DoReservation" action to be invoked (I want the form to be submitted).
How can I achieve something like that?
What I can suggest is , adding a new property to your view model and call it ActionType.
public string ActionType { get; set; }
and then change your cshtml file like below
#using (Html.BeginForm())
{
<div id="mytargetid">
...some inputs*#
</div>
<button type="submit" name="actionType" value="Recalculate" >Recalculate price</button>
<button type="submit" name="actionType" value="DoReservation" >Submit</button>
}
in post action method based on ActionType value you can decide what to do !
I noticed that in your comments you mentioned you need to return partial and replace if with returning partial , no problem , you can use
#using (Ajax.BeginForm("DoProcess", new AjaxOptions { UpdateTargetId = "mytargetid", InsertionMode = InsertionMode.Replace }))
and in controller change your action to return partial view or java script code to redirect page
public ActionResult DoProcess(FormModel model)
{
if (model.ActionType == "Recalculate")
{
return PartialView("Test");
}
else if (model.ActionType == "DoReservation")
{
return JavaScript(string.Format("document.location.href='{0}';",Url.Action("OtherAction")));
}
return null;
}

Resources