Alternate Way To Write Razor Code/ Can HTML Work Instead? - c#

Is there anyway to rewrite razor code in html format to get the same results?
I honestly did not try anything but google a few solution but could not get help
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h3> Create new Genre</h3>
<hr />
<div class="form-group">
#Html.LabelFor(m => m.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(m => m.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(m => m.Name, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div>
<input type="submit" value="Create" class="btn btn-sm btn-success" />
#Html.Partial("_BackToListPartial")
</div>
IS there a pure html version of this code that will produce the same result without using lambda expression?
No errors, just asking for alternate ways

If you are using ASP.NET Core then you can use Tag Helpers, which look like standard HTML.
For example, #using (Html.BeginForm()) could instead use the form tag helper:
<form asp-controller="MyController" asp-action="MyAction" method="post">
</form>

Related

Adding bootstrap classes with html helper methods not working?

Is there any way to add bootstrap classes like form-control to asp.net mvc html helper methods like #html.Textbox("searchString");?
this is the code I have in the view
#this is the html output for the search bar taking searchstring param from controller in htmlhelper#
#using (Html.BeginForm())
{<div class="jumbotron">
<div class="row">
<div class="col-md-12">
<p>
Search: #Html.TextBox("SearchString")
<input class="btn btn-info" type="submit" value="Search" />
</p>
</div>
</div>
</div>
}
It seems like everything is playing nice with bootstrap except the #Html.Textbox and its messing up my UI.
is there a way to affect the #Html.Textbox with bootstrap form-control class?
ps the "SearchString" variable comes from my controller.
Yes.
You have the possibility to add HtmlAttributes:
#Html.TextBox("SearchString", null, new { #class = "form-control" })
And if you're using a property from your #model:
#Html.TextBoxFor(m => m.Property, new { #class = "form-control" })
#Html.TextBox("SearchString", null, new {#class="form-control"});
One variation of the #Html.TextBox helper takes an anonymous object that you can use to pass in HTML attributes. You would use it like:
#Html.TextBox("SearchString", null, new { #class = "form-control" })

remove items to a bound list model in ASP MVC.NET

I followed an online tutorial to dynamically add items to a bound list model using ajax, which works perfectly. (http://www.mattlunn.me.uk/blog/2014/08/how-to-dynamically-via-ajax-add-new-items-to-a-bound-list-model-in-asp-mvc-net/comment-page-2/#comment-68909)
My question is, how would I correctly remove items from the list?
Right now what I have done is add a delete link which when clicked removes the item from the view. However, when I submit the form I noticed that the modelState is no longer valid and it has null entries for the item that was removed from the view. So I guess the model is not being updated.
Test.cshtml
#model TesterManager.Models.Test
<div class="form-group">
#Html.LabelFor(model => model.Software, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="form-group">
<div class="col-md-5">
#Html.DropDownListFor(m => m.Software, TesterManager.Models.Helper.GetTestSoftwares(), "Choose a USB Card", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Software, "", new { #class = "text-danger" })
</div>
<div class="col-md-5">
#Html.EditorFor(model => model.Version, new { htmlAttributes = new { #class = "form-control", #title = "Enter a USB FW Version", #placeholder = "Enter a USB FW Version" } })
#Html.ValidationMessageFor(model => model.Version, "", new { #class = "text-danger" })
</div>
<div class="col-md-2">
Delete
</div>
</div>
</div>
</div>
AdminTesterConfigurations.cshtml (snippet):
#model TesterManager.Models.AdminTesterConfigurations
<div class="form-group">
<div class="col-md-6">
....
</div>
</div>
<hr />
<div class="form-group">
<div class="col-md-12">
<h3>Test Software</h3>
<div id="test-list">
#Html.EditorForMany(x => x.Tests, x => x.Index)
</div>
<input type="button" id="add-test" value="Add" />
</div>
</div>
RequestEditViewModel.cshtml:
#model TesterManager.Models.RequestEditViewModel
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.EditorFor(model => model.ShippingLocation)
#Html.EditorFor(model => model.RequesterTesterConfigurations)
#Html.EditorFor(model => model.AdminTesterConfigurations)
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
Edit.cshtml:
#model TesterManager.Models.RequestEditViewModel
#Styles.Render("~/Content/Edit")
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Scripts
{
<script>
jQuery(document).ready(function ($) {
$('#add-test').on('click', function () {
jQuery.get('/TesterManager/Request/AddTest').done(function (html) {
$('#test-list').append(html);
});
});
});
</script>
}
#using (Html.BeginForm())
{
<h2>Edit</h2>
#Html.AntiForgeryToken()
#Html.EditorFor(x => x);
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
RequestController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(RequestEditViewModel request)
{
if (ModelState.IsValid)
{
Request domainRequest = new Request(request);
requests.Add(domainRequest);
return RedirectToAction("Index");
}
return View(request);
}
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult AddTest()
{
var request = new RequestEditViewModel();
request.AdminTesterConfigurations.Tests.Add(new Test());
return View(request);
}
I realized that the problem was that when I would remove the item from the list in the view, I was not removing the hidden input for the collection indexer as well. I updated the code to remove the hidden input and it works fine now.

Render view with modified Model

I´m new in MVC, and I´m working in a simple FORM, but,I have a problem,
for some reason I want to change the bound model in the controller operation and
render the view, but this not happen.
For example:
public class Product{
int id {get; set;}
string description {get; set;}
}
and the controller method:
[POST]
public ActionResult Edite(Product p){
p.description = "HELLOOOOOO!!!"
return View(P);
}
the view:
#model WebSite.Models.Product
#{
ViewBag.Title = "Modificar (Product)";
}
<h2>Modificar (Product)</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4></h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Guardar" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Volver a la Lista", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
but in the rendered view, the description of the product is not "HELLOOOOO!!!!".
Why MVC render the view with the user entered values and not with the new model I want?
maybe isn't the best way to resolve the problem, but this post solved my problem:
Asp.net MVC ModelState.Clear

MVC model binding, Initial Model Missing

In this instance I have two pages, in the post method of the first I return the view/viewmodel of the second like so :
[HTTPPost]
public Task<ActionResult> Page1(Page1Model model)
{
var Page2Model = GrabDataMethod(model);
return View("Page2", Page2Model); //Point 1
}
[HTTPPost]
public Task<ActionResult> Page2(Page2Model model //Point 2)
{
var updatedModel= RunFiltersMethod(model)
return View(updatedModel);
}
Now, in this case Page2 renders properly from (Point 1) with all values passed in above from the GrabDataMethod. However, when I POST for Page2 the Page2Model I receive at (Point 2) has none of the original entries, e.g. everything not modified directly by Page2 itself is null or default (in fact it seems the model from the post method is a new model entirely). I've made a horrible workaround for the time being, but I need a proper fix, is there any reason that this would be happening?
Page2 View Code
#model Mvc2013.Models.Page2Model
#using (Html.BeginForm("Page2", "Controller"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
<div class="row">
<div class="col-md-12">
#Html.Kendo().Chart(<!-- code removed, this is working -->)
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="col-md-8">
#Html.LabelFor(model => model.Prop1, new { #class = "control-label" })
</div>
<div class="col-md-4">
#Html.EditorFor(model => model.Prop1, new { #class = "control-label" })
#Html.ValidationMessageFor(model => model.Prop1)
</div>
</div>
<div class="col-md-3">
<div class="col-md-8">
#Html.LabelFor(model => model.Prop2, new { #class = "control-label" })
</div>
<div class="col-md-4">
#Html.EditorFor(model => model.Prop2, new { #class = "control-label"})
#Html.ValidationMessageFor(model => model.Prop2)
</div>
</div>
</div>
<!-- This carries on similarly for lots more attributes -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Inside the Beginform you should add #Html.HiddenFor(model => model.Something) where the Something are the properties which you want back on the postback.
If you don't then the property values will be default values.

Handle button clicks in a .NET MVC application/ calling a controller from a cshtml page

I am working on a MVC web application and not sure where I should add my code to handle button clicks. I have a cshtml view that is being rendered by a controller. When the view is displayed I need to handle several buttons that are being displayed - such print, email, etc. Where should I add my code to handle these and can you give me an example on how to implement it?
<input id="save-button" type="submit" class="btn btn-primary" onclick="submitOrder();" value="Print Order" />
The submitOrder() call is what I need to handle.
1.If your button is not posting back to a form you can call the controller like this:
<input type="button" value="Something" onclick="location.href='#Url.Action("ActionName", "ControllerName")'" />
there are several overloads to this method, some accepting many more parameters.
2.If you are posting back a form and your input button is within that form, then your input button will post back to the controller.
The login page in the default mvc application has examples of both of the 2 options I've mentioned above.
Here's a part of that page:
<section id="loginForm">
#using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Use a local account to log in.</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.UserName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Password)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Log in" class="btn btn-default" />
</div>
</div>
<p>
#Html.ActionLink("Register", "Register") if you don't have a local account.
</p>
}
</section>
You also have several options to call a controller using JQuery Ajax. That's a little more sophisticated, though.

Categories