form submit always hit in mvc index method while enable unobtrusive javascript enabled - asp.net-mvc-4

MY form element submit is not working while enable unobtrusive javascript mode. it always hits in index method. how to resolve this issue. while enable unobtrusive mode with form submit successfully.
public ActionResult Index()
{
var Data = value;
ViewBag.dataSource = Data;
return View();
}
public ActionResult frmbtn()
{
return View("Index");
}
[HttpPost]
public void Formposting()
{
// it not hit while enable unobtrusive in webconfig
. . .
}

You didn't show view code it's difficult to locate the problem. you can match your code with given below:
#using (Html.BeginForm("Formposting", "ControllerName", FormMethod.Post, new { id = "formid" }))
{
}
Donot forget to replace "ControllerName" with actual controller name.
Or if you have blank in beginform like below
#using (Html.BeginForm())
{
}
You need to add one more "Action" with httppost and model
public ActionResult Index(Your Model Here){ return View();}

Related

Tag helpers not working with DynamicRouteValueTransformer

ASP.NET Core's tag helpers appear not to be working in combination with DynamicRouteValueTransformer.
Here's an MCVE: let's say we have a simple controller with two actions...
public class GenericController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Add()
{
return View();
}
}
... and the Index view links to the Add action with the asp-action tag helper:
<!DOCTYPE html>
<html>
<body>
<a asp-action="Add">Add new!</a>
</body>
</html>
When we now open /Generic in a browser and inspect the page, we'll notice that ASP.NET generated the expected href value for the controller action:
Add new!
So far, so good. Now let's create a DynamicRouteValueTransformer which routes all requests to that same controller...
public class Transformer : DynamicRouteValueTransformer
{
public override ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
{
if (values.ContainsKey("controller"))
{
values["originalController"] = values["controller"];
values["controller"] = "Generic";
}
return new ValueTask<RouteValueDictionary>(values);
}
}
... and let's set it up for endpoint routing in Startup.cs...
services.AddSingleton<Transformer>();
...
app.UseEndpoints(endpoints =>
{
endpoints.MapDynamicControllerRoute<Transformer>("{controller=Home}/{action=Index}/{id?}");
});
After opening /Generic (or any other route, e.g. /Foobar) in a browser and inspecting the page, we'll now notice that asp-action tag helper is no longer working:
Add new!
Since the href value is empty, the link is no longer working. It looks the dynamic routing broke the tag helper.
Any suggested fix or workaround?

Redirecting to a response view with a model does not keep model properties

I have a form view that submits form data to the post action on a controler and then redirects to another view that uses logic to display either a success or failure, but the new view just shows blank values for model properties. Here is the post action:
[HttpPost]
public ActionResult ContactUs(TTT.Models.ContactUsModel model)
{
logger.Info(model.URL + "Contact Us Form submitted");
var userkey = model.ValidationKey;
var sessionkey = Session["ContactUsKey"];
var lastsubmission = Session["ContactUsTime"];
model.Response = "success";
//first check if honeypot was populated via a bot and if so send it to the success page without doing anything
if (model.WorkAddress != "")
{
logger.Info("honeypot triggered");
return View("ContactUsResponse", model);
}
I'll leave out the remainder of the controler, but
And here is the view it's redirecting to:
#using TTT.Models
#using Sitecore.Mvc
#model ContactUsModel
<h1>#Model.Title</h1>
<div>#Model.Body</div>
<div>
#if (#Model.Response == "fail")
{
#Model.Failure;
} else
{
#Model.Success;
}
</div>
Instead of returning a new view, call RedirectToAction and return new view from that controller.
[HttpPost]
public ActionResult ContactUs(TTT.Models.ContactUsModel model)
{
//--- Code omitted for brevity
if (model.WorkAddress != "")
{
logger.Info("honeypot triggered");
return RedirectToAction("ContactUsResponse", new { response = model });
}
}
public ActionResult ContactUsResponse(TTT.Models.ContactUsModel response)
{
return View(model)
}

ASP.NET MVC 4 - ListBoxFor, send selectedValue in ActionLink

I have a list of model. I want to retrieve the listBoxSelectedValue to send it in my actionLink to edit it.
This is my view :
#using (Html.BeginForm())
{
#Html.ListBoxFor(a => a.SelectedApplis, new SelectList(ViewBag.Applis,"ID","Name", Model.SelectedApplis))<br/>
#Html.ActionLink("Add","Create","Application")<br/>
#Html.ActionLink("Edit","Edit","Application", null, new { listAppId = Model.SelectedApplis})<br/>
#Html.ActionLink("Delete","Delete","Application")<br/>
}
I created a class "ListBoxApplication" with the List which will contain the selectedValue of the ListBox.
public class ListBoxApplication
{
public IEnumerable<int> SelectedApplis { get; set; }
public ListBoxApplication()
{
SelectedApplis = new List<int>();
}
}
I have 2 controllers : Application and Home
In HomeController, I created the model ListBoxApplication which contain the List. In my ViewBag.Applis, i have all my ApplicationModel.
public ActionResult Index()
{
ListBoxApplication listeApplis = new ListBoxApplication();
ViewBag.Applis = ApplicationModels.GetListApplications();
return View(listeApplis);
}
In my ApplicationController :
public ActionResult Edit(ListBoxApplication listAppId)
{
// I WANT TO RETRIEVE MY listAppId HERE, but it is always 'null'
return View();
}
So I think my problem is in the actionLink :
#Html.ActionLink("Edit","Edit","Application", null, new { listAppId = Model.SelectedApplis})
Me Edit Method is not is the actual controller (Home/Index). I need to send the selectedValue of my ListBox in my actionLink to (Application/Edit).
The listAppId is always 'null'. It doesn't retrieve the value... Is there a mistake in my actionLink ?
Thanks for advance
I don't believe that action links will trigger a postback to the server. Try this instead:
#Html.ActionLink("Delete","Delete","Application")<br/>
#Html.ActionLink("Add","Create","Application")<br/>
#using (Html.BeginForm("Detail","Application"))
{
#Html.ListBoxFor(a => a.SelectedApplis, new SelectList(ViewBag.Applis)) //not sure what the other params you had here were for, but it should work like this
<br/>
<input type="submit" name="Edit" value = "Edit"/>
#*added in response to comment*#
<input type="submit" name="Delete" value = "Delete"/>
<input type="submit" name="Add" value = "Add"/>
}
If you plan on having all of those buttons post back to the server, you could also use ajax (and javascript) to accomplish this same goal, without needing to write out a form for each individual button. Both ways would work just fine, multiple forms is technically easier though.
public ActionResult Detail(ListBoxApplication listAppId, bool Edit, bool Add, bool Delete)
{
if(//check your bools here){
}
return View();
}

access child action parameter in its view

public class AController : Controller
{
public ActionResult Index()
{
return View();
}
}
and Index view goes like
...
#Html.Action("Index", "BController", new { HasEditPermission = true })
...
BControler goes like
public class BController : Controller
{
public ActionResult Index()
{
return PartialView();
}
}
and this Index Partial view goes like
...
#if (!string.IsNullOrEmpty(Request.Params["HasEditPermission"]) && bool.Parse(Request.Params["HasEditPermission"]))
{
// some html rendering
}
...
here when I do Request.Params["HasEditPermission"] in the partial view, I get null.. but if I include HasEditPermission as a parameter to my Index action of BController then I get the value..
I think, I am not getting it from Request.Params because actual request is to AController Index action which doesn't include this parameter.
But I am wondering how is it binding the value to HasEditPermission parameter of Index action(suppose if I have it there) of BController?
Please could someone tell me how do I access it directly in the view? (I am aware using ViewBag in Index is an option)
You can use ValueProvider.GetValue("HasEditPermission").RawValue to access the value.
Controller:
public class BController : Controller
{
public ActionResult Index()
{
ViewBag.HasEditPermission = Boolean.Parse(
ValueProvider.GetValue("HasEditPermission").RawValue.ToString());
return PartialView();
}
}
View:
...
#if (ViewBag.HasEditPermission)
{
// some html rendering
}
...
Update:
Request.Params gets a combined collection of QueryString, Form, Cookies, and ServerVariables items not RouteValues.
In
#Html.Action("Index", "BController", new { HasEditPermission = true })
HasEditPermission is a RouteValue.
you can also try something like this
ViewContext.RouteData.Values["HasEditPermission"]
in your View and subsequent child action views as well..

How can I implement multiple forms using a single view?

I am having a scenario where I need to implement two forms using a single view... There will be a home page having a form each for LogIn and SignUp (similar to Facebook homepage). I created a view for my home page (Index.cshtml) that contains the razor code for both my forms.
[#using (Html.BeginForm("LogIn", "Home", FormMethod.Post))]
[#using (Html.BeginForm("SignUp", "Home", FormMethod.Post))]
However, upon clicking the 'Log In' button for LogIn form or clicking 'Sign Up' button for SignUp form, the runtime throws an error basically saying that I still need to create views for both LogIn and SignUp actions, even though I have already implemented the HTML forms in my index.cshtml
[NOTE: I am not using ASP.NET membership provider. And this question is generally for two forms, can be any two forms.]
So my question is: Do I really need to create two more views named LogIn.cshtml and SignUp.cshtml? Won't this cause code duplication? I'm quite new to MVC 4 and I hope you understand what I'm trying to do here, so all I want to know is whether there is any other way to implement this? (jQuery, AJAX or something)
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult LogIn()
{
return View();
}
[HttpPost]
public ActionResult LogIn(Account acc)
{
// some code
return View();
}
[HttpGet]
public ActionResult SignUp()
{
return View();
}
[HttpPost]
public ActionResult SignUp(Account acc)
{
// some code
return View();
}
}
You could specify the view you want to be returned:
[HttpGet]
public ActionResult SignUp()
{
return View("LogIn");
}