sitefinity ActionResult missing query string - sitefinity

I have widget and in the ActionResult method it get the query string as parameters. The widget takes the query string and calls a API. Is there anyway I can display a message to the view if its missing the query string?
Code
public ActionResult Index(string UserId, string BlogId)

Yep, do whatever you want
if(String.IsNullOrEmpty(UserId)){
// you get the idea
}
I would do one of the following
Add a property to the model, then handle that state in the view
Load a custom view that's just the message (cleanest)
Check for the empty querystring and do a return this.RedirectPermanent(url); to add the querystring to the page so there's no way it loads without something.

Related

In ASP.NET Core, is it possible to generate a URI in the controller for a Get action that takes two parameters? If so how?

I have an association controller called ConnectionManagerCategoriesController. It has two Get methods on it. One to get all Categories for a ConnectionManager and one to only retrieve one Categoy for the ConnectionManager based upon the name. I have a Post to create a new category and I am trying to generate a uri for LinkGenerator. However when the URI that is created, it uses the GetConnectionManagerCategories method instead of the GetConnectionManagerCategory. I dont know why or how to do it differently.:
[Route("api/connectionmanagers/{connectionManagerID:int}/categories")]
[ApiController]
public class ConnectionManagerCategoriesController : ControllerBase
{
private readonly LinkGenerator _linkGenerator;
[HttpGet]
public async Task<ActionResult<IEnumerable<ConnectionManagerModel>>> GetConnectionManagerCategoriesAsync(int connectionManagerID){}
[HttpGet("{categoryName}", Name = "GetConnectionManagerCategoryAsync")]
public async Task<ActionResult<ConnectionCategoryModel>> GetConnectionManagerCategoryAsync(int connectionManagerID, string categoryName){}
[HttpPost]
public async Task<ActionResult<ConnectionCategoryModel>> AddConnectionCategoryAsync(int connectionManagerID, string categoryName, [FromHeader(Name = "x-requestid")] string requestId)
{
var url = _linkGenerator.GetUriByRouteValues(HttpContext,
"GetConnectionManagerCategoryAsync",
values: new { connectionManagerID, categoryName = commandResult.CategoryName });
return Created(url, commandResult);
}
It returns the following uri to Swagger: 'http://localhost:6704/api/connectionmanagers/1/categories?categoryName=Almost'
However, when I log the uri in the code it is: http://localhost:6704/api/connectionmanagers/1/categories/newvalueadded
Is this even possible?
You have to show how are trying to run the action, in order to get some explanations. Routing is very tricky and it is better not to try to create routes the way you are creating.
IMHO , it is always a good idea to define the whole route, not just the part. Especially if you use Swager
[HttpGet("{~/api/connectionmanagers/{connectionManagerID:int}/categories/{categoryName}")]
public async Task<ActionResult<ConnectionCategoryModel>> GetConnectionManagerCategoryAsync(int connectionManagerID, string categoryName){}

Blazor Application - pass a Query String to the app on startup

I have a Blazor application how can I pass a Query String to the app on startup?
I want to pre-populate a form field and query a database with the query string value on startup.
Something like this `http://www.somesite.com?Company=Google
I have seen the following - using query string in pages. But how to you accept the query string on start up?
https://www.mikesdotnetting.com/article/340/working-with-query-strings-in-blazor
Where in the app page or code - Startup.cs / Program.cs - do you check for the query string.
thx in advance
This Microsoft article will explain it better than I can:
https://learn.microsoft.com/en-us/aspnet/core/blazor/routing?view=aspnetcore-3.1
Here is a summary of relevant parts.
On your page you can have this:
#page "/Users/{text}"
Then in your code create a parameter:
[Parameter]
public string Company { get; set; }
Then if you navigate to: yoursite.com/Users/Google
your parameter will be populated, and you can do any loading / or other prerendering in OnInitializedAsync method.
// this is from one of my projects
protected override async Task OnInitializedAsync()
{
// load the Categories
this.Categories = await HelpCategoryService.GetHelpCategoryList();
}
You can have multiple routes on the same page, so you could have:
#page "/Users/
#page "/Users/{Company:string}"
Maybe that points you in the right direction.

Data is not inserting to the database

I am new to asp .net MVC 4.
I have one text box and the text box value I am fetching from one table.But while clicking on submit button this value I want to insert into different table , which is not inserting and showing error.It is taking value as null.
coding
View
#Html.TextBox("empname", (string)ViewBag.empname, new { #readonly = "readonly" })
controller
[HttpGet]
public ActionResult Facilities()
{
mstEmpDetail emp = new mstEmpDetail();
emp = db.mstEmpDetails.Single(x => x.intEmpId == 10001);
ViewBag.empname = emp.txtEmpFirstName;
return View();
}
[HttpPost]
public ActionResult Facilities(TrnBusinessCardDetail bc)
{
var empname1 = ViewBag.empname;
bc.txtfirstName = empname1;
db.TrnBusinessCardDetails.Add(bc);
db.SaveChanges();
return RedirectToAction("Facilities");
}
While I was working with normal text box it was inserting properly,but when I have retrieve
fro DB then i am getting this problem ?
How to solve this problem ?
Viewbag is a one way street - you can use it to pass information to the view, but you cannot use it to get the information from the view. The statement ViewBag.empname in your POST method has a value of null in your code.
As suggested by #dotnetom, ViewBag is a one way street. MVC is stateless so a POST request is not a "Round Trip" from previous get request. Thus your ViewBag can not hold its state.
MVC can determine (and construct) your action parameters from Form Parameters. In your case you have added a textbox with name "empname". So you should get this value as parameter in your POST request.
[HttpPost]
public ActionResult Facilities(TrnBusinessCardDetail bc, string empname)
{
bc.txtfirstName = empname;
db.TrnBusinessCardDetails.Add(bc);
db.SaveChanges();
return RedirectToAction("Facilities");
}
This would be simplest of solution given your problem. More appropriate would be binding your textbox directly with you model property. This way you will not have to worry about retrieving and assigning property value to model in your controller.
I think the problem is when you are using var empname1 = ViewBag.empname; in post controller because ViewBag.empname lost its value at that time.

asp.net mvc add parameter with each action view

I have a site which have many action like article, blog, news, stories, myths, books, audio, video.
Now I want if i pass a query string in index action like
wwww.mysite.com/english
then every action must be have this parameter automatically like
wwww.mysite.com/article/englishwwww.mysite.com/blog/englishwwww.mysite.com/news/englishwwww.mysite.com/stories/englishwwww.mysite.com/myths/englishwwww.mysite.com/books/englishwwww.mysite.com/audio/englishwwww.mysite.com/video/english
Please help me and suggest a good way
Store the passed passed parameter in a session variable and then access on each action. Example:
public ActionResult Index(string lang)
{
Session["Language"]= lang;
return View();
}
And then fetch in other actions like:
public ActionResult News()
{
string lang= Session["Language"].ToString();
// Do something with the lang...
return View();
}

MVC returns page as a file

I have an mvc4 project and I am getting a weird result. Whenever I sumit a form and fire up a postback, if the entry is correct it redirects me to the success page which is good. But when my input is invalid and it has to return to the same page, to display the error message, it comes up as a downloadable file. Can anybody please tell me what is going on?
<HttpPost()>
Public Function Collection(oColInfo As CollectionInfoVM) As ActionResult
If ModelState.IsValid Then
oColInfo.CollectionDate = DateTime.Now
m_oAppBase.Collection.AddGroupCollection(oColInfo)
Return View("_Success")
Else
ViewData.Add("PaymentTypes", PaymentType.Dictionary.ToSelectList(oColInfo.PaymentType))
ViewData.Add("PaidBy", PaidBy.Dictionary.ToSelectList(oColInfo.PaidBy.ToString()))
Return View(oColInfo)
End If
End Function
EDIT 1 :
I also found out that my controller is returning my view as JSON. That's why IE is asking me if i wanted to download it. Why is my default return type JSON?
EDIT 2 :
The response type is application/json instead of text/html.
EDIT 3 :
It works when I remove the Html.RenderAction("MainMenu", "Menu") from my layout
Controller action looks like this;
Public Function MainMenu() As PartialViewResult
' Let's see if we have an unprocessed turnin from this district
Dim dtDate As Date = DateTime.Now
Dim colDistStatus As List(Of DistrictStatus) = m_oAppBase.TurnIn.GetNextTurnInStatus()
ViewData.Add("DistrictStatus", colDistStatus)
Return PartialView("_MainMenu")
End Function
Why is my default return type JSON?
ActionResult includes JsonResult too.so when you use ActionResult and you post data from ajax ,your default returns Json.
But when my input is invalid and it has to return to the same page
for validate form in client side,you have to use valid method in your script.it validates form in clientside and doesnt post to your action.
JqueryCode:
if ($('form').valid()) {
$.ajax({});
});
Okay, so looking around I found out that there was a partial view on the page with attribute that returns JSON and when I submit the button this get's fired up too and returned to the browser. I removed the HttpPost attribute and it fixed it. sigh