I am trying to send a query like below from UI to controller.
name='abc' and title='def'
I am trying to use lambda expression on controller to filter this query. But I am struggling hard to pass ui query to controller and make it as lambda expression.
Could you please throw some idea with example where i can pass sql query(string) as parameter and use it in controller action method as lambda expression. Any link or logic should be fine for me to try further.
[HttpGet]
public virtual ActionResult QueriedProjects(string builtQuery)
{
var Helpera = new Helpera(true);
var myProjectDetails = Helpera.myProjectDetails (null);
var myProjectDetails = new myProjectDetails ()
{ GetMyProjectDetails = myProjectDetails };
return View(myProjectDeails)
}
UI
on button click I am generating a query as string with entered values in query builder
Generated String: name='abc' and title= 'def'
If you pass values like this:
Contoller/QueriedProjects?name=abc&title=def
You need to have 2 parameters in your controller method like:
public virtual ActionResult QueriedProjects(string name, string title)
Related
I am working on a project (Developed by using .Net Core), I have set some routes and one of them is not working e.g.
1) routes.MapRoute("HRDetail", "H-R/{TName}/{MId}", new { controller = "ABC", action = "XYZ1" });
2) routes.MapRoute("CL", "{SName}/{CName}/{CId}", new { controller = "ABC", action = "XYZ2" });
I have written the code in the same sequence in Startup class, and my action methods are as follows.
public async Task<IActionResult> XYZ2(string SName, string CName, Int16 CId)
{//for route#2}
public async Task<IActionResult> XYZ1( string TName, Int64 MId)
{//for route#1}
Now I want to hit on XYZ1 by using route#1 and the link (to hit on XYZ1 is being created dynamically) is like this http://localhost:4321/H-R/UK/1234. But the problem is that when i click on this link, it always take me to XYZ2 method.
I didn't set any route on controller or action method level.
Is there any solution plz?
It seems, The route are getting confused. There are two ways you can fix this.
1) in your first route specify the regular expression which will say that first parameter will be a fixed string as H-R
2) in you second route specify the regular expression which will say that first parameter will never be H-R
1st
routes.MapRoute("HRDetail", "{ActionName}/{TName}/{MId}", new { controller = "ABC", action = "XYZ1" }, new{ActionName = "$your regularexpression to include only H-R$"});
OR
routes.MapRoute("CL", "{SName}/{CName}/{CId}", new { controller = "ABC", action = "XYZ2" }, new {SName = "$your regularexpression to exclude H-R$" });
PS: you need to put some efforts for regular expression
So in my mvc 5 app, I got this default 'Index' action, which simply redirects to the search action, with the default model values:
[Route]
public ActionResult Index()
{
var model = new T();
return RedirectToAction("Search", model);
}
What i got puzzled about is how i end up with the url like '.../search?xxx=xxx...'? Is there anything i can do to customize or at least inject/replace the url generation, especially the query string part? e.g. i might want to display 1/0 for bool properties in the search model, and customize query string key names etc?
and why would someone vote down for my question? psst...
The query string generated depend on the model property name and type + value you passed in.
For example, say if your pass in model is like
public class MyModel
{
bool IsSort{get;set;}
}
If your model is like this and IsSort value is true, then you will get url like /search?IsSort=true
Say you want to change your query string to 1/0 instead of true or false, then create viewModel which has property string then assing it properly like:
public class MyModel
{
string IsSort{get;set;}
}
var model = new MyModel();
model.IsSort = true? "1":"0";
same apply to querystring key (which correspond to property name)
#Html.Partial("~/Areas/WO/Views/PartialContent/_FirstPage.cshtml", new ViewDataDictionary { { "WOID", WOID } })
In my Page i am accessing Partial view in the above way.
I need to pass WOID(view data dictionary) value from query string, For that i am using following Code
#{
var desc = Html.ViewContext.HttpContext.Request.QueryString.Get("ID");
Uri referrer = HttpContext.Current.Request.UrlReferrer;
string[] query = referrer.Query.Split('=');
int WOID = Convert.ToInt32(query[1]);
}
But the issue is this code is working in all browsers except I.E. i Need to Solve this problem.
Please help me
Instead of this you can have this value as part of you model and use that.That is the standard and recommeded way .
In your action method you can have these as parameter.Your query string value will get bind to this parameter
public ActionResult ActionMethod(int ID)
{
Model.WOID = WOID;
// Other logic
return View(Model)
}
Next step you can add this as a property to your view model or add it to ViewData dictionary and then access it in your partial view.
I have an MVC app where users fill in a 4-step form then go to a "confirm" screen. On the confirm screen, if they select to modify their info I use RedirectToAction to take them back to the first step view, and I pass a URL parameter "modify=true", which tells the controller to use the session object already created as opposed to creating a new object from the DB and displaying an empty form. But once they submit the form for step 1 I want to send them from my controller to the step 2 view along with the "modify=true" parameter. There doesn't seem to be a way to return a viewmodel to a view and also pass a query string parameter. How can I accomplish this?
I have considered adding a bool to the viewmodels to signify "inReview" but i use different viewmodels for each of these views and they're all pretty clean, it seems like this bool would muck things up a bit.
I have also considered adding the bool to viewbag or viewdata, but then i'd be using the submit button to pass that value and the "modify=true" parameter would drop off the URL, possibly confusing the user and definitely confusing the code.
Thanks
If you use the Html.BeginForm() helper (without parameters) it will automatically append existing query string parameters to the generated form action attribute. If you use some of the other overloads such as Html.BeginForm("SomeAction", "SomeController", FormMethod.Post) then you're gonna lose those parameters. This could be easily fixed by writing a custom helper that will take into account those parameters:
public static class HtmlHelpers
{
public static IDisposable BeginRequestForm(this HtmlHelper html, string action, string controller, FormMethod method)
{
var builder = new TagBuilder("form");
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
var routeValues = new RouteValueDictionary();
var query = html.ViewContext.HttpContext.Request.QueryString;
foreach (string key in query)
{
routeValues[key] = query[key];
}
builder.MergeAttribute("action", urlHelper.Action(action, controller, routeValues));
builder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
html.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag));
return new MvcForm(html.ViewContext);
}
}
and then use in your view (after bringing it into scope of course):
#using (Html.BeginRequestForm("SomeAction", "SomeController", FormMethod.Post))
{
...
}
You can either use ViewBag or your view model. You just need to pass the value somehow to the view:
ViewBag.modify = true;
return View(model);
Then in your view:
Html.BeginForm("MyAction", "MyController", new { modify = ViewBag.modify })
First post time,
I've been playing around with MVC abit... I have a view which has multiple input fields, some of these fields can be blank on post.
The action method inside the controller for the post looks something like this
public ActionResult Filter(int? id, string firstName, string lastName, bool? isMember)
I've been using the DynamicQuery extension which has been kicking around in order to perform dynamic Linq querys on my database and I've encapsulated this in a Search object which is passed to the data access layer for execusion.
However, I also have a customized ViewData object which is passed back to the view for displaying the input values and the results of the query.
It all looks a little nasty in code as I'm having to set both the Search object properties AND the ViewDatas.
public ActionResult Filter(int? id, string firstName, string lastName, bool? isMember) {
var search = new Search {
Id = id,
FirstName = firstName,
LastName = lastName,
Member = isMember
};
var memberViewData = new MemberViewData {
Id = id,
FirstName = firstName,
LastName = lastName,
Member = isMember
};
memberViewData.Results = _dataRepository.GetMember(search);
return View("Search", memberViewData);
}
Am I over thinking this and really should just pass the values to the data access layer and populate the ViewData in the controller, or is there a much more elegant pattern or practise I could use?
Sorry if this seems dump, not allot of people to bounce ideas off and time to dig into the framework.
Use modelbinder to bind data
According to your snippet MemberViewData class has the Results property in addition to properties of Search class. So first step would be to make MemberViewData derive from Search and define a constructor that accepts Search instance as parameter and assigns it's basic properties from it. Next I would change the action method like so:
public ActionResult Filter(Search search)
{
return View("Search", new MemberViewData(search)
{
Results = _dataRepository.GetMember(search)
});
}
Like Tadeusz mentioned, a ModelBinder can help build the MemberViewData for you, which would leave only the results to be fetched.
You could also decide on creating a presentation service that understands how to build this view data object and simply delegate to it. I'd prefer the model binder approach here though.