How is # used in MVC Razor and when is it required? - html

I'm fairly new at MVC 3 but I came across a rather curious problem.
I'm using the Razor syntax, and according to VS, I don't need to prefix # to statements if they are immediately preceded with another # statement, or once inside the code, the prefix # is no longer required.
So here is my code in my View:
#using (Html.BeginForm("StudentSelect", "Home", FormMethod.Post, new { id = "sSelect" })) {
Html.HiddenFor(m => m.SelectedStudent);
foreach (Classes.CStudent item in Model.Students)
{
<div class="studentSelect">
<div class="studentname">#item.StudentName</div>
<div>#item.Address</div>
</div>
}
}
Take not that the Html.HiddenFor and foreach lines do not have # prefix.
The generated HTML should produce a <form> followed by a <input type="hidden"> field.
However, upon checking the HTML on the generated page, the hidden input field is missing.
<form action="/Home/StudentSelect" id="sSelect" method="post">
<div class="studentSelect">
<div class="studentname">Name1</div>
<div>AAA</div>
</div>
<div class="studentSelect">
<div class="studentname">Name2</div>
<div>Address1</div>
</div>
</form>
Am I doing something wrong? Why isn't the hidden input not rendered?
Any clues would help. Thanks
By the way, this code compiles correct. However, if I prefix # in front of Html.HiddenFor my code does not compile and Visual Studio produces an error.

The # serves two purposes. One to trigger "code mode" and one to shorthand Response.Write.
The instance of # preceding the using triggers "code mode".
The instance of # preceding item.Address is equivalent to Response.Write(item.Address);.
You still require it for Html.HiddenFor as this returns an MvcHtmlString output that needs to be written to the response stream.
This line:
Html.HiddenFor(m => m.SelectedStudent);
should be:
#Html.HiddenFor(m => m.SelectedStudent)
Notice the ; is no longer required.

Related

laravel blade form not routing to a named route

I am new to named routing in Laravel 5.5 and I am facing a strange thing while trying to perform an action of a form;
Setups and Explanations:
I set up my routes in web.php
Route::post('questions/save_bulk', 'QuestionsController#save_bulk')->name('save_bulk');
Route::post('questions/store_bulk', 'QuestionsController#store_bulk')->name('store_bulk');
Then I set up store_bulk and save_bulk in QuestionsController:
public function store_bulk(Request $request)
{
//$x = some DB::selects statements;
return view('questions.store_bulk', ['x'=> $x]);
}
public function save_bulk(Request $request){
dd($request);
}
And finally this is my blade form in questions.store_bulk which should lead to QuestionsController.save_bulk:
<form method="post" action="{{route('save_bulk')}}">
{{csrf_field()}}
/* some codes and input fields */
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit"/>
</div>
</form>
Problem
The problem is that when I submit this form, instead of taking me to the desired route and perform dd($request), it is just refreshing the page without the inputs I had as if Laravel took the last post form which returned the view questions.store_bulk.
Though this is the exact same way I used to get into the view questions.store_bulk in the first place, a strange thing occurs: when I try to inspect elements in the blade page I get the following:
<form method="post" action="http://127.0.0.1:8000/questions/store_bulk">
/* some codes and inputs */
</form>
in the codes the route should go to QuestionsController.save_bulk but when inspecting the HTML it says it goes to http://127.0.0.1:8000/questions/store_bulk, and if I inspect and change the route manually inside the HTML and write http://127.0.0.1:8000/questions/save_bulk it goes to the right route and perform dd($request).
Question
Why is this happening? am I missing something?
Note
I am using Laravel 5.5 locally on my PC preparing a website.
I've had similar issues with routing.. You can change the url.. e.g. questions/somethingelse/save_bulk.. so the urls won't clash.. Or run php artisan cache:clear or view:clear incase you implemented a page caching system

(m => m.Email) meaning (ASP.NET) and how to get a user's username

I am brand new to web development. What little experience I have is in C# Unity and Java. The code below was taken from the screen followed by the Google authentication/login screen. I am trying to set the user's Google name to the username on the website. I was wondering if someone could help me out and maybe explain what (m => m.Email) means.
Thank you so much!
#model Start.Models.ExternalLoginConfirmationViewModel
#using (Html.BeginForm("ExternalLoginConfirmation", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" })) {
#Html.AntiForgeryToken()
<hr />
<div class="form-group">
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email)
</div>
</div>
<input type="submit" />
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
in the code #Html.TextBoxFor(m => m.Email) the variable m represents the current model, which is set at the top of the file as Start.Models.ExternalLoginConfirmationViewModel.
m => m.Email means "get the Email property from this model". If you were to look at the model (in Visual Studio put your mouse cursor on ExternalLoginConfirmationViewModel and press F12) you will most likely see that there is an Email property on it.
So #Html.TextBoxFor(m => m.Email) creates the HTML needed to show a textbox for the email address of the current model.
In the end it will probably generate some HTML that looks like this:
<input type="text" value="bob#example.com" id="some-generated-id-here" />
This is using the MVC Razor syntax, which you might want to do some reading up on.
https://learn.microsoft.com/en-us/aspnet/web-pages/overview/getting-started/introducing-razor-syntax-c
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/razor
http://www.tutorialsteacher.com/mvc/razor-syntax
Here's the slightly more technical explanation. The => operator denotes a lambda, which can be thought of as a function that returns its value in place. The stuff on the left side (m) is the parameter(s) to the "function", and the stuff on the right side is what will be returned from the "function". Given that, m => m.Email means, essentially, "return the Email property of what I pass in here".
However, when it comes to things like HtmlHelpers, what you're passing as the first parameter there is actually Expression<Func<TModel, TProperty>>, so let's unwrap that. Func<TModel, TProperty> is the actual type of that lambda we just talked about. Func is a generic type, with two (or more) type parameters. Here, the first type parameter is TModel, and corresponds to the type of the "left side" of the lamda, i.e. the type of the thing we're passing in. The TProperty type parameter is the type of the "right side" of the lambda, i.e. the thing we're returning.
Expression is a wrapper applied to things like Func, and builds what's called an "expression tree" out of the lambda. This expression tree, among other things, allows the inspection of what's inside that lambda, so you can determine things like the name of the property that's being returned. The HtmlHelpers, then, use this information to do things like generating id and name attributes, which obviously need to match the property name. This is actually an important thing to recognize as a lot of new developers get confused and think they can pass in just about anything to an HtmlHelper as the expression. That's not the case, because you're not dealing with a value, but rather an expression representing a value. For example, the following would not work at all:
#Html.TextBoxFor(m => m.Email.ToLower())
Because it's not a valid expression, even though it works for the purpose of the lambda.

Viewmodel in partial and duplicates

I have really strange problem. So, my structure is like this
<div id="tasks">
#Html.Partial("_Tasks", tasks)
</div>
and in _Tasks I do a foreach through all tasks and for each task I have additional partial
...
#Html.Partial("_Time", new TimeViewModel(task))
...
and inside of _Time I have form
...
#Html.TextBoxFor(m => m.Name)
....
So in a view I render a partial and then inside again multiple partials and inside it a form. When I perform a page load, it works. Problem begins with when I'm using ajax, so I perform edit to Time and post to server and update #tasks with returned html.
I'm my controller action I have...
...
return View("_Tasks", tasks);
and the problem now is that all inputs generated by #Html.TextBoxFor(m => m.Name) have the same value. Why? If I do
#Html.DisplayFor(m => m.Name)
I works just fine. I also tried with
#Html.TextBoxFor(m => m.Name, new { Value = Model.Name })
and it works, but it looks hackish to me.
The question is, why is get this behavior? Why does all TextBoxFor have same value?
Default model binder in ASP.NET MVC determines how to map the values to your model by using name attributes on input tags. All the html helpers generate markup with that in mind.
So when you write
#Html.TextBoxFor(m => m.Name)
It generates something like this:
<input type="text" name="Name" />
However when you use this helper in a partial view and try to bind a model that's a property of the main model, it won't work. Html helper in the partial will still generate markup thinking its model is the main model. So your input will be binded to main model's Name property. You can take a look a this question for solving this problem. Also keep in mind the default binder can not pick up complex collections when you handle post requests.

CakePHP hidden _method POST

When using the FormHelper->create(...), the HTML that gets rendered looks like this:
<form action="/blogs/add" method="post" accept-charset="utf-8">
<div style="display:none;">
<input type="hidden" name="_method" value="POST">
</div>
<!-- omitted: form inputs -->
</form>
Why is that div with the display:none; style there? How do I make it not show up?
UPDATE: Just to be clear, I'm wondering why both the div AND the hidden input inside the div show up. They don't seem to be necessary, and therefore I don't want them to be there.
For anyone coming to this recently, there is a simple solution to this now that doesn't involve a custom helper. Using the FormHelper templates, the block of code in question is generated by the 'hiddenBlock' template. (See the full list of default templates here: https://api.cakephp.org/3.2/class-Cake.View.Helper.FormHelper.html#%24_defaultConfig).
So, to amend the example given in CakePHP's documentation to match this case and remove the wrapping <div> around the hidden <input> for _method (assuming HTML5):
// In your View class
$this->loadHelper( 'Form' , [ 'templates' => 'app_form' ] );
// in config/app_form.php
return [
'hiddenBlock' => '{{ content }}'
];
I was confronted with this problem because I recently implemented a Content Security Policy that doesn't allow inline styling, and I thought I should share my working solution.
The div is there to be valid HTML.
Non-block-level elements (such as <input>) are not valid directly inside <form> tags until HTML5. Source
Edit: To answer your question, you can't easily get rid of it. It's hard-coded into FormHelper::create(), you'd have to override that method in a custom helper. Why is it bothering you anyways?
This link might help you.
Whenever you use FormHelper->create() method ,A hidden input field is generated to override the default HTTP method. You can also change it by passing type option. Kindly ask if it not worked for you.
Try:
echo $this->Form->create('User', array(
'inputDefaults' => array(
'div' => false
)
));
The divs won't be created on any input of the form.
use hiddenField => false property

Ajax and Grails for Dummies

I am a rookie Grails user and I am completely new to AJAX. I am not exactly grasping the concept of AJAX, and the material online is fragmented.
From my understanding, in grails if I wanted to execute a method in one of my controllers when a part of my HTML doc loads I could simply use something along the lines of
<div onload="${remoteFunction(action:"foo", update:"foo"...)}" ...>
How is the response from the call to the hypothetical foo returned and how can I access it in a js function?
Can I return an object from a class I created from my hypothetical foo action?
On the return of the foo action you can put simple html as text or render some objects that can be used in the view.
Here you have all the info about the Controller "render"
http://grails.org/doc/latest/ref/Controllers/render.html
You can have a that will be update with that data and work there with it. Then you can access to the Html and data inside that "foo" div with javascript like you usually do.
For example:
Controller.groovy
// renders text to response
render '<div id="bar" onclick="alert($('bar').val())>some text</div>'
View.gsp
//Makes the call and updates foo
<div onload="${remoteFunction(action:"foo", update:"foo"...)}" ...>
<div id="foo" name="foo"></div>
Output
<div onload="theAjaxJavascriptFunctionThatGrailsWillInject" ...>
<div id="foo" name="foo">
<div id="bar" onclick="alert($('bar').val())">some text</div>
</div>
I you return some object from the Controller.grooy then you have to treat it like this in you View.gsp
//Makes the call and updates foo
<div onload="${remoteFunction(action:"foo", update:"foo"...)}" ...>
<div id="foo" name="foo">
${myObject.theValueIWant}
</div>
I added a javascript alert but you can do it the way you like, there are lots of ways to do it.
Hope it helps :)