6
<% using (Html.BeginForm("DisplayCustomer","Customer",FormMethod.Post))
{ %>
Enter customer id :- <%= Html.TextBox("Id",Model)%> <br />
Enter customer code :- <%= Html.TextBox("CustomerCode",Model) %><br />
Enter customer Amount :- <%= Html.TextBox("Amount",Model) %><br />
<input type="submit" value="Submit customer data" />
<%} %>

Using Razor

    @using (Html.BeginForm("DisplayResult", "DisplayCustomer", FormMethod.Post)) { 
    @Html.ValidationSummary(true);

    @:Enter customer id :- @Html.TextBox("Id",Model)
    @:Enter customer code :-@Html.TextBox("Code",Model)
    @:Enter customer Amount :-@Html.TextBox("Amount",Model)
    <input type="submit" value="Enter the value" />

} 

Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'TextBox' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

@using (Html.BeginForm("DisplayResult", "DisplayCustomer", FormMethod.Post)) { 
    @Html.ValidationSummary(true);

    @:Enter customer id :- <input type="text" name="Id" />
    @:Enter customer code :-<input type="text" name="Code" />
    @:Enter customer Amount :-<input type="text" name="Amount" />
    <input type="submit" value="Enter the value" />

}

This works correctly

What am I doing wrong .I am trying to use the razor equivalent of the code given in first section.The second part is the razor code attempt and third works when only form is used .I also want to know if nest is the reason the error is happening

EDIT:-

  @:Enter customer id :- @Html.TextBox("Id")
  @:Enter customer code :-@Html.TextBox("Code")
  @:Enter customer Amount :-@Html.TextBox("Amount")

If I do not use model then everything works perfectly

Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class DisplayCustomerController : Controller
    {
        //
        // GET: /DisplayCustomer/
        [HttpPost]
        public ViewResult DisplayResult()
        {
            Customer objCustomer = new Customer();
            objCustomer.Id = Convert.ToInt16(Request.Form["Id"].ToString());  //101; 
            objCustomer.Amount =Convert.ToDouble(Request.Form["Amount"].ToString());// 80.00;
            objCustomer.Code = Request.Form["Code"].ToString();//"IE100"; 

            return View("DisplayResult", objCustomer);
        }
        public ActionResult ShowForm() 
        {

            return View("ShowForm");
        }

    }
}

Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
    public class Customer
    {
        //private string Code;
      //  private int Id;
        //private double Amount;
        public String Code
        {
            get;
            set;
        }
        public int Id
        {
            get;
            set;
        }
        public double Amount
        {
            get;
            set;
        }

    }
}

View(ShowForm)

@{
    ViewBag.Title = "ShowForm";
}

<h2>ShowForm</h2>

@using (Html.BeginForm("DisplayResult", "DisplayCustomer", FormMethod.Post)) { 
    @Html.ValidationSummary(true);

    @:Enter customer id :- @Html.TextBox("Id")
    @:Enter customer code :-@Html.TextBox("Code")
    @:Enter customer Amount :-@Html.TextBox("Amount")
    <input type="submit" value="Submit" />

}
codefreaK
  • 3,584
  • 5
  • 34
  • 65
  • You are passing your entire model to each textbox. It should be `Model.Code` or whatever property name you need to display. I don't think that's the cause of the error, but something that should be fixed regardless. –  Jul 24 '16 at 23:38
  • @PhillipXT okay thanks for that but yes you are right that is not the reason for the error – codefreaK Jul 24 '16 at 23:39
  • 1
    How have you declared your model, with `@model dynamic`? – user247702 Jul 24 '16 at 23:40
  • The correct usage would be `@Html.TextBoxFor(m => m.Id)` or `@Html.TextBox("Id")` (and use `LabelFor()` for the label). But as noted above, that is not the cause of the error. Most likely you have not declared the model correctly - `@model yourModel` –  Jul 24 '16 at 23:41
  • @StephenMuecke Apart from label I am finding difficult to find what the issue is for the time being I can wing it with the third way but the real thing is missing – codefreaK Jul 24 '16 at 23:45
  • @SachinDivakar, You need to declare the model at the top of the view - assuming you model is `class MyModel`, then in the view add `@model yourAssembly.MyModel` –  Jul 24 '16 at 23:46
  • @SachinDivakar What is Model in your razor, Are you taking it from viewbag – Saket Choubey Jul 24 '16 at 23:50
  • http://www.codeproject.com/Articles/207797/Learn-MVC-Model-View-Controller-step-by-step-in#Lab 4:- Creating simple MVC data entry screen.I am studying mvc using the following tutorial – codefreaK Jul 24 '16 at 23:56
  • @SachinDivakar, You still have not confirmed if you have the `@model ...` statement at the top of your view (if you do not, or you have used `@model dynamic` then you will get that error. –  Jul 25 '16 at 00:01
  • @StephenMuecke I Have given the full code – codefreaK Jul 25 '16 at 00:07
  • @SachinDivakar, Just add `@model MvcApplication1.Models.Customer` as the first line in the view and it will work fine. –  Jul 25 '16 at 00:08
  • @StephenMuecke if you are using strict type and using the model isnt it suppose to appear automatically ?and I am facing a weird glitch I dont know why the same thing which was working is showing 404 so now I cant test its okay now after restarting – codefreaK Jul 25 '16 at 00:16
  • No, you need to declare the model in the view (as per my previous comment). But there are a lot of bad practices in your code its hard to imagine anything works correctly :) And your methods do not make much sense - why is the GET method `ShowForm()` and the POST method `DisplayResult()` which returns a different view. And what is the purpose of the POST method - it does not do anything? –  Jul 25 '16 at 00:21
  • @StephenMuecke I am just winging it and learning stuff by trying it out it works perfectly thanks post it under as answer I will accept it.I was actually confused with about a thing there was another thing see there was another functionality when user submits the form it goes to another action and then it does a if check and displays the result.Basically I wanted it to be in same view but I thought it will trigger the if check the first time I load page so Instead of dealing with it I tried this since I am learning the working – codefreaK Jul 25 '16 at 00:25
  • @SachinDivakar, Give me 30 min or so - I'll add some other comments about what you should be doing. –  Jul 25 '16 at 00:26
  • @StephenMuecke Wow thanks a lot man I appreciate your help I used to do web development with c# and .net back in the day now refreshing everrything and I was taking a break for almost a year – codefreaK Jul 25 '16 at 00:29

1 Answers1

11

Your error occurs because you have not declared the model in the view. Modify the view to

@model MvcApplication1.Models.Customer // add this
@{
    ViewBag.Title = "ShowForm";
}
....

Note the error will also occur if you use @model dynamic

I would however suggest a number of changes to your code. Firstly, always using a view model, especially when editing (refer What is ViewModel in MVC?). It is also preferable to use the ***For() methods to generate you controls, and you curret use of @Html.TextBox("Id", Model) would mean the each textbox would display "MvcApplication1.Models.Customer", not the value of the property. In addition, use LabelFor() to generate labels associated with your controls, and include ValidationMesageFor() for validation

public class CustomerVM
{
    [Display(Name = "Customer Id")]
    [Required(ErrorMesage = "Please enter the customer id")]
    public int? Id { get; set; }
    [Display(Name = "Customer Code")]
    [Required(ErrorMesage = "Please enter the customer code")]
    public string Code { get; set; }
    [Display(Name = "Customer Amount")]
    [Required(ErrorMesage = "Please enter the customer amount")]
    public double? Amount { get; set; }
}

and the view will be

@model yourViewModelAssembly.CustomerVM
....

@using (Html.BeginForm("DisplayResult", "DisplayCustomer", FormMethod.Post))
{
    @Html.AntiForgeryToken();
    @Html.ValidationSummary(true);
    @Html.LabelFor(m => m.Id)
    @Html.TextBoxFor(m => m.Id)
    @Html.ValidationMessageFor(m => m.Id)
    @Html.LabelFor(m => m.Code)
    @Html.TextBoxFor(m => m.Code)
    @Html.ValidationMessageFor(m => m.Code)
    ....
}

Side note: If the Id property is the PK, then that should not be included in the view as an editable control.

Its also unclear why you are submitting to a different method, and in any case your POST method does not do anything with the data (e.g. saving it). It just returns the same data back again, but to a different view. Typically your methods would be

public ActionResult Create()
{
    var model = new CustomerVM();
    return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CustomerVM model)
{
    if (!ModelState.IsValid)
    {
        return View(model)
    }
    var customer = new Customer
    {
        Code = model.Code,
        Amount = model.Amount
    }
    .... // save the Customer and redirect
}
Community
  • 1
  • 1
  • its regarding a different issueI am trying to do jquery ajax form post with webmethod and right now I am stuck with a situation the form also has fileupload part so what I am trying to do is send the submitted data as json format to webmethod .But right now I am forced to use 1 parameter variable for each text box and I am not able to retrieve the uploaded file .I have understood that form can be serialized but how to to receive the form at webmethod as a parameter and deserialize it – codefreaK Aug 03 '16 at 22:18
  • Your going to need to ask a new question with the relevant details and code (you can add a link to it here but I wont get a chance to look at it for a couple of hours) –  Aug 03 '16 at 22:20
  • http://stackoverflow.com/questions/38754763/ajax-jquery-form-post-using-web-methods-c-sharp-asp-net this is my question thanks – codefreaK Aug 03 '16 at 22:37
  • @SachinDivakar, That's webforms code (its been a long time since I used that), but have a look at [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) for serializing the form including file inputs and submitting it using ajax –  Aug 03 '16 at 22:41
  • is web methods a outdated technology and have every one moved on to MVC and – codefreaK Aug 03 '16 at 22:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/119056/discussion-between-stephen-muecke-and-sachin-divakar). –  Aug 03 '16 at 22:55