I have the following ActionResult in my controller
[HttpGetAttribute]
public ActionResult _UpdateAlertNote(int recordId)
{
DealActionUpdateAlertNoteViewModel vm = new DealActionUpdateAlertNoteViewModel();
dtDeal_v10_r1.Manager objMan = new dtDeal_v10_r1.Manager(ref mobjSecurity);
dtDeal_v10_r1.Deal objDeal = default(dtDeal_v10_r1.Deal);
objDeal = objMan.GetDealObject(recordId, true);
vm.Message = objDeal.AlertMessage;
vm.IsDefaultStyle = objDeal.Alert_UseDefaultStyle;
vm.BackgroundColor = objDeal.Alert_BackgroundColor;
vm.FontColor = objDeal.Alert_FontColor;
vm.DealId = recordId;
return PartialView(vm);
}
Also the following ActionResult
[HttpPost]
public ActionResult _UpdateAlertNote(DealActionUpdateAlertNoteViewModel vm)
{
dtDeal_v10_r1.Manager objMan = new dtDeal_v10_r1.Manager(ref mobjSecurity);
objMan.UpdateAlertMessage(vm.DealId, vm.Message, vm.IsDefaultStyle, vm.FontColor, vm.BackgroundColor);
return this.PartialView("_action", vm.DealId);
}
When I execute this code it the "DealId" comes up as 0 in the Post.
I checked the Get and the DealId is being stored in the vm.DealId but is not passed through to the Post method.
I am not sure why it isn't passing could someone help me out with this.
****EDIT json added***
DealerSocket.TakeAction.updateDealAlertNote = function () {
var controller = "/DealAction/_UpdateAlertNote?mDeal_ID=";
var formId = "_UpdateDealAlertNoteFormElement";
DealerSocket.TakeAction.PostActionAndRefresh(formId, controller);
};
When you are posting an HTML Form element to a POST action, you need to make sure the value you pass to the view is stored in a Form element.
In this case of yours you will need something like:
<input type="hidden" value="#vm.DealId" />
within the <form> tag that you are Posting to the action.
Only elements inside the <form> tag will be serialized and sent to the Action.
I'm just getting started with MVC5 (from WebForms), and dropdownlist bindings are giving me some fits.
I'd like to get this working using a GET request back to the page, with a selected value parameter. I'm hopeful that I can specify the route arguments in the form itself, so I'd like to reference the DDL's SelectedValue.
<p>
#using (Html.BeginForm("Index", "Profile", FormMethod.Get, new { id = WHATDOIPUTHERE} )) {
#Html.AntiForgeryToken()
#Html.DropDownList("ApplicationID", new SelectList(ViewBag.ApplicationList, "ApplicationID", "ApplicationName", ViewBag.SelectedApplicationId), new {onchange = "this.form.submit();"})
}
</p>
I can make it work with a POST form, but that requires a second controller method so I end up with
public ActionResult Index(long? id) {
ConfigManager config = new ConfigManager();
//handle application. default to the first application returned if none is supplied.
ViewBag.ApplicationList = config.GetApplications().ToList();
if (id != null) {
ViewBag.SelectedApplicationId = (long)id;
}
else {
ViewBag.SelectedApplicationId = ViewBag.ApplicationList[0].ApplicationID; //just a safe default, if no param provided.
}
//handle profile list.
List<ProfileViewModel> ps = new List<ProfileViewModel>();
ps = (from p in config.GetProfilesByApp((long)ViewBag.SelectedApplicationId) select new ProfileViewModel(p)).ToList();
return View(ps);
}
//POST: Profile
//read the form post result, and recall Index, passing in the ID.
[HttpPost]
public ActionResult index(FormCollection collection) {
return RedirectToAction("Index", "Profile", new {id = collection["ApplicationId"]});
}
It would be really nice to get rid of the POST method, since this View only ever lists child entities.
What do you think?
You can update your GET action method parameter name to be same as your dropdown name.
I also made some small changes to avoid possible null reference exceptions.
public ActionResult Index(long? ApplicationID) {
var config = new ConfigManager();
var applicationList = config.GetApplications().ToList();
ViewBag.ApplicationList = applicationList ;
if (ApplicationID!= null) {
ViewBag.SelectedApplicationId = ApplicationID.Value;
}
else
{
if(applicationList.Any())
{
ViewBag.SelectedApplicationId = applicationList[0].ApplicationID;
}
}
var ps = new List<ProfileViewModel>();
ps = (from p in config.GetProfilesByApp((long)ViewBag.SelectedApplicationId)
select new ProfileViewModel(p)).ToList();
return View(ps);
}
From my surfacecontroller I wish to append the current querystring to the redirect action. I cant seem to find any appropriate method of doing this.
The page the form gets sent from contains a tab that is shown by appending the querystring to the url. The form is submitted from this tab, and I want the thank you message to be displayed on the same tab.
The querystring is #inquery
From my surfacecontroller:
[HttpPost]
public ActionResult HandleFormSubmit(InquiryFormModel model)
{
if (!ModelState.IsValid)
{
return CurrentUmbracoPage();
}
// Mail date goes here...
TempData["success"] = true;
return RedirectToCurrentUmbracoPage();
}
As you have properly guessed, I want #inquery appended to the URL returned by the RedirectToCurrentUmbracoPage() method.
Thanks!
Where you return the current page, add in a viewbag object with the querystring contained within. Have this field stored in a hidden input in your HTML and have your clientside javascript test for it and append it to the URL if it exists.
if (!ModelState.IsValid)
{
ViewBag.URLString = "stringhere"
return CurrentUmbracoPage();
}
then in your HTML.
<input id="URLString" type="hidden" />
And in your javascript (if you're using jQuery)
$(document).ready(function(){
window.location.href += $("#URLString").val();
});
I haven't fully qualified this code so it won't work as it is, but it's there more to give you an idea.
I have the following routes:
routes.MapRoute("Event Overview", "{city}/{type}/{id}",
new {city="LA", controller = "BaseEvent", action = "EventOverview"}, new {city = new CityConstraint()});
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
And, several links on my site:
#Html.ActionLink("Make", "EventOverview", "BaseEvent", new { id = eventInfo.Key.OID, type = eventInfo.Key.XPObjectType.TypeName.GetShortTypeName(), activeTab = "#scheduleLink", session = eventInfo.Key.EventSchedules[0].SessionId, hall = eventInfo.Key.EventSchedules[0].HallId, client = eventInfo.Key.EventSchedules[0].BasePlace.PremieraClientId}, null)
#Html.ActionLink("Make", "EventOverview", "BaseEvent", new { id = eventInfo.Key.OID, type = eventInfo.Key.XPObjectType.TypeName.GetShortTypeName(), activeTab = "#scheduleLink", }, null)
This is `EventOverview action:
public ActionResult EventOverview(int id, string type, string activeTab,string hall, string session, string client, string count)
{
var model = CreateEventViewData<EventViewData>(id, type);
model.ActiveTab = activeTab;
model.ScheduleCount = count;
model.SessionId = session;
model.HallId = hall;
model.ClientId = client;
return View("Controls/EventsInfo/EventInfo", model);
}
In the first link passing many parameters, and all shows in browser's address field:
This is for firts link:
http://localhost:62291/LA/Film/36?activeTab=%23scheduleLink&session=15&hall=65&client=2&count=1
This is for second link:
http://localhost:62291/LA/Film/36?activeTab=%23scheduleLink
I want something like that:
http://localhost:62291/LA/Film/36
What ways to hide parameters in an address line are?
UPDATE:
$(document).ready(function () {
var link = $(".btn_buy_ticket").find("a").click(function (e) {
e.preventDefault();
$.post($(this).attr("href"));
});
})
[HttpPost]
public ActionResult EventOverview(int id) // just for test
{
return RedirectToAction("EventOverview", new {id = id});
}
public ActionResult EventOverview(int id, string type, string activeTab,string hall, string session, string client, string count)
{
var model = CreateEventViewData<EventViewData>(id, type);
model.ActiveTab = activeTab;
model.ScheduleCount = count;
model.SessionId = session;
model.HallId = hall;
model.ClientId = client;
return View("Controls/EventsInfo/EventInfo", model);
}
All actions are called, but my EventInfo view not loaded.
You could use POST instead of GET. So you could replace the link with a form containing hidden fields for the parameters that you don't want to appear in the query string:
#using (Html.BeginForm("EventOverview", "BaseEvent", new { id = eventInfo.Key.OID, type = eventInfo.Key.XPObjectType.TypeName.GetShortTypeName() }, FormMethod.Post, null))
{
#Html.Hidden("activeTab", "#scheduleLink")
#Html.Hidden("session", eventInfo.Key.EventSchedules[0].SessionId)
#Html.Hidden("hall", eventInfo.Key.EventSchedules[0].HallId)
#Html.Hidden("client", eventInfo.Key.EventSchedules[0].BasePlace.PremieraClientId)
<button type="submit">Make</button>
}
How to hide URL Parameters
If you want to hide URL parameters, you go to debug properties and you select the radiobutton option and specify thatc
specificpage:
http://localhost:61757/TicketDataUpload/templateupload?projectid=6497&userid=7336
This is the parameter URL. If you want to hide like this:
http://localhost:61757/Controller/index
You have to put in a specific page as when you open the page, it will not display URL parameters.
My (kinda ugly) solution: leave the code behind as is, then after the html doc has loaded (at which point the server has already made use of your query string data), use history.pushState in javascript to change the url in the address bar like so:
$(document).ready(function () {
let hrefWithoutQueryString = window.location.href.split('?')[0];
// args below are 'state' (irrelevant for me), 'title' (so far,
// ignored by most browsers) and 'url' (will appear in address bar)
history.pushState({ }, '', hrefWithoutQueryString);
});
For a split second the query string will appear in the address bar, but after the js above has run, everything including and after the '?' in your url will be gone.
Obviously, a side effect is that it alters your browser's session history but this wasn't an issue for me.
And note that I have passed in an empty state into pushState--again, this was not an issue for me but could cause problems depending on how the routing of your application is set up and whether it makes use of the state variable.
I'm having a bit of a brain fart; it must be Monday...
I have an MVC form, which allow the user to submit an image.
The image is saved to a folder, then I want to redirect to another Controller and Action to display the image.
What are my options for passing the image name and path back to the controller action to display the graphic?
// Handles the updload, contains a control (ascx)
// and the control's action method is in another controller
public ActionResult Index()
{
return View();
}
// I want this page to display the image uploaded in the Upload.ascx control
// that is in the index method above:
public ActionResult Result()
{
ViewData["MyImage"] = ???
}
Thanks much.
Where is the image being stored? In your content area or in a database? If it's in a database, then I'd construct the controller/action url to display that image form the db. If it's in your content area, then you can construct the url based on the name of the uploaded file. I'd probably create a model rather than passing the url in view data, but view data is a valid (i.e., it works) alternative.
public ActionResult Result( int id ) // db storage
{
return View( new UploadModel
{
ImageUrl = Url.Action( "display", "image", new { id = id }
} );
}
public ActionResult Result() // content area
{
var imageName = ... get image name from ??? ...
return View( new UploadModel
{
ImageUrl = Url.Content( "~/content/images/uploads/" + iamgeName );
});
}