Передача данных объекта модели из представления, в контроллер, в модель? - PullRequest
1 голос
/ 29 декабря 2011

Я новичок в ASP.net MVC (примерно через неделю), так что все еще есть некоторая путаница ...

Как мне передать текущую модель представлений вконтроллер, чтобы я мог получить данные модели?

Вид

@model KineticBomardment.Models.Blog.BlogPost

@{
    ViewBag.Title = "Index";
}


@using (Html.BeginForm())
{
@Html.ValidationSummary(false)

    <fieldset class="block">
       <div class="input">
            @Html.LabelFor(x => x.Title)
            @Html.EditorFor(x => x.Title)
        </div>
         <div class="input">
            @Html.LabelFor(x => x.ShortDescription)
            @Html.EditorFor(x => x.ShortDescription)
        </div>

        <div class="button">
            @Html.ActionLink("Submit", "CreateNewBlogEntry", "Admin" );
        </div>

    </fieldset>

}

У меня тогда есть контроллер

 public ActionResult CreateNewBlogEntry(Models.Blog.BlogPost currentBlogModel)
    {
        if (ModelState.IsValid)
        {
            currentBlogModel.CreatePost();
            return Content("Created!");
        }

        return View();
    }

И модель

public class BlogPost
{
    public int Id { get; set; }

    [Required]
    [Display(Name="Title of Blog Post")]
    public string Title { get; set; }

    public DateTime DateCreated { get; set; }

    [Required]
    [Display(Name = "Short Description")]
    public string ShortDescription { get; set; }

    public string LongDescription { get; set; }

    public int HeaderImage { get; set; }

    public ICollection<BlogPost> GetAllPosts()
    {
        ICollection<BlogPost> posts = new List<BlogPost>();

        using (SqlConnection connection = new   SqlConnection(ConfigurationManager.ConnectionStrings["KineticBombardment"].ToString()))
        {
            using (SqlCommand cmd = new SqlCommand("select title, datecreated, shortdescription from blogentries where id > 0", connection))
            {
                cmd.Parameters.Clear();
                connection.Open();
                cmd.ExecuteNonQuery();

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while(reader.Read())
                    {
                        this.ShortDescription = reader["shortdescription"].ToString();
                        this.Title = reader["title"].ToString();
                        this.DateCreated = Convert.ToDateTime(reader["datecreated"].ToString());
                        posts.Add(this);
                    }
                }

                return posts;
            }
        }
    }

    public void CreatePost()
    {
        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["KineticBombardment"].ToString()))
        {
            using (SqlCommand cmd = new SqlCommand("insert into blogentries (shortdescription, datecreated, blogtype, title) values (@shortdescription, @datecreated, @blogtype, @title)", connection))
            {
                cmd.Parameters.Clear();
                connection.Open();

                cmd.Parameters.Add("@shortdescription", SqlDbType.VarChar, 500).Value = this.ShortDescription;
                cmd.Parameters.Add("@datecreated", SqlDbType.DateTime).Value = DateTime.Now;
                cmd.Parameters.Add("@blogtype", SqlDbType.Int).Value = 1;
                cmd.Parameters.Add("@title", SqlDbType.VarChar, 255).Value = this.Title;

                cmd.ExecuteNonQuery();

            }
        }
    }

}

1 Ответ

2 голосов
/ 29 декабря 2011

Изменение:

    <div class="button">
        @Html.ActionLink("Submit", "CreateNewBlogEntry", "Admin" );
    </div>

Кому:

    <input type="submit" class="button" />

и

public ActionResult CreateNewBlogEntry(Models.Blog.BlogPost currentBlogModel)
{
    if (ModelState.IsValid)
    {
        currentBlogModel.CreatePost();
        return Content("Created!");
    }

    return View();
}

до

public ActionResult CreateNewBlogEntry()
{
    return View();
}

[HttpPost]
public ActionResult CreateNewBlogEntry(Models.Blog.BlogPost model)
{
    if (ModelState.IsValid)
    {
        currentBlogModel.CreatePost();
        return Content("Created!");
    }
    return View();
}

Я сделал несколько предположений, но это должно сработать

...